Project

General

Profile

Download (80.2 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * captiveportal.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2016 Electric Sheep Fencing, LLC
7
 * All rights reserved.
8
 *
9
 * originally part of m0n0wall (http://m0n0.ch/wall)
10
 * Copyright (c) 2003-2006 Manuel Kasper <mk@neon1.net>.
11
 * 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

    
58
/* include all configuration functions */
59
require_once("config.inc");
60
require_once("functions.inc");
61
require_once("filter.inc");
62
require_once("radius.inc");
63
require_once("voucher.inc");
64

    
65
function get_default_captive_portal_html() {
66
	global $config, $g, $cpzone;
67

    
68
	$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
	$htmltext = <<<EOD
73
<html>
74
<body>
75
<form method="post" action="\$PORTAL_ACTION\$">
76
	<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
	<tr height="10" style="background-color:#990000">
81
		<td style="border-bottom:1px solid #000000">
82
			<font color='white'>
83
			<b>
84
				{$translated_text1}
85
			</b>
86
			</font>
87
		</td>
88
	</tr>
89
	<tr>
90
		<td>
91
			<div id="mainlevel">
92
			<center>
93
			<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
					<tr>
101
						<td>
102
							<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
								<br />
112
								<div id='loginbox'>
113
								<table>
114
									<tr><td colspan="2"><center>{$translated_text2}</td></tr>
115
									<tr><td>&nbsp;</td></tr>
116
									<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
									<tr><td>&nbsp;</td></tr>
119

    
120
EOD;
121

    
122
	if (isset($config['voucher'][$cpzone]['enable'])) {
123
		$translated_text = gettext("Enter Voucher Code:");
124
		$htmltext .= <<<EOD
125
									<tr>
126
										<td class="text-right">{$translated_text} </td>
127
										<td><input name="auth_voucher" type="text" style="border:1px dashed;" size="22"></td>
128
									</tr>
129

    
130
EOD;
131
	}
132

    
133
	$translated_text = gettext("Continue");
134
	$htmltext .= <<<EOD
135
									<tr>
136
										<td colspan="2"><center><input name="accept" type="submit" value="{$translated_text}"></center></td>
137
									</tr>
138
								</table>
139
								</div>
140
							</center>
141
							</div>
142
						</td>
143
					</tr>
144
					</table>
145
					</center>
146
					</div>
147
					</center>
148
				</td>
149
			</tr>
150
			</table>
151
			</center>
152
			</div>
153
		</td>
154
	</tr>
155
	</table>
156
	</center>
157
</form>
158
</body>
159
</html>
160

    
161
EOD;
162

    
163
	return $htmltext;
164
}
165

    
166
function captiveportal_load_modules() {
167
	global $config;
168

    
169
	mute_kernel_msgs();
170
	if (!is_module_loaded("ipfw.ko")) {
171
		mwexec("/sbin/kldload ipfw");
172
		/* make sure ipfw is not on pfil hooks */
173
		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
	}
178
	/* Activate layer2 filtering */
179
	set_sysctl(array("net.link.ether.ipfw" => "1", "net.inet.ip.fw.one_pass" => "1"));
180

    
181
	/* 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
		set_sysctl(array("net.inet.ip.dummynet.io_fast" => "1", "net.inet.ip.dummynet.hash_size" => "256"));
185
	}
186
	unmute_kernel_msgs();
187
}
188

    
189
function captiveportal_configure() {
190
	global $config, $cpzone, $cpzoneid;
191

    
192
	if (is_array($config['captiveportal'])) {
193
		foreach ($config['captiveportal'] as $cpkey => $cp) {
194
			$cpzone = $cpkey;
195
			$cpzoneid = $cp['zoneid'];
196
			captiveportal_configure_zone($cp);
197
		}
198
	}
199
}
200

    
201
function captiveportal_configure_zone($cpcfg) {
202
	global $config, $g, $cpzone, $cpzoneid;
203

    
204
	$captiveportallck = lock("captiveportal{$cpzone}", LOCK_EX);
205

    
206
	if (isset($cpcfg['enable'])) {
207

    
208
		if (platform_booting()) {
209
			echo "Starting captive portal({$cpcfg['zone']})... ";
210

    
211
			/* remove old information */
212
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
213
		} else {
214
			captiveportal_syslog("Reconfiguring captive portal({$cpcfg['zone']}).");
215
		}
216

    
217
		/* init ipfw rules */
218
		captiveportal_init_rules(true);
219

    
220
		/* kill any running minicron */
221
		killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
222

    
223
		/* initialize minicron interval value */
224
		$croninterval = $cpcfg['croninterval'] ? $cpcfg['croninterval'] : 60;
225

    
226
		/* double check if the $croninterval is numeric and at least 10 seconds. If not we set it to 60 to avoid problems */
227
		if ((!is_numeric($croninterval)) || ($croninterval < 10)) {
228
			$croninterval = 60;
229
		}
230

    
231
		/* write portal page */
232
		if (is_array($cpcfg['page']) && $cpcfg['page']['htmltext']) {
233
			$htmltext = base64_decode($cpcfg['page']['htmltext']);
234
		} else {
235
			/* example/template page */
236
			$htmltext = get_default_captive_portal_html();
237
		}
238

    
239
		$fd = @fopen("{$g['varetc_path']}/captiveportal_{$cpzone}.html", "w");
240
		if ($fd) {
241
			// Special case handling.  Convert so that we can pass this page
242
			// through the PHP interpreter later without clobbering the vars.
243
			$htmltext = str_replace("\$PORTAL_ZONE\$", "#PORTAL_ZONE#", $htmltext);
244
			$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
			if ($cpcfg['preauthurl']) {
250
				$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
251
				$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
252
			}
253
			fwrite($fd, $htmltext);
254
			fclose($fd);
255
		}
256
		unset($htmltext);
257

    
258
		/* write error page */
259
		if (is_array($cpcfg['page']) && $cpcfg['page']['errtext']) {
260
			$errtext = base64_decode($cpcfg['page']['errtext']);
261
		} else {
262
			/* example page  */
263
			$errtext = get_default_captive_portal_html();
264
		}
265

    
266
		$fd = @fopen("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html", "w");
267
		if ($fd) {
268
			// Special case handling.  Convert so that we can pass this page
269
			// through the PHP interpreter later without clobbering the vars.
270
			$errtext = str_replace("\$PORTAL_ZONE\$", "#PORTAL_ZONE#", $errtext);
271
			$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
			if ($cpcfg['preauthurl']) {
277
				$errtext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $errtext);
278
				$errtext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $errtext);
279
			}
280
			fwrite($fd, $errtext);
281
			fclose($fd);
282
		}
283
		unset($errtext);
284

    
285
		/* write logout page */
286
		if (is_array($cpcfg['page']) && $cpcfg['page']['logouttext']) {
287
			$logouttext = base64_decode($cpcfg['page']['logouttext']);
288
		} else {
289
			/* example page */
290
			$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
			$logouttext = <<<EOD
295
<html>
296
<head><title>{$translated_text1}</title></head>
297
<body>
298
<span style="font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">
299
<b>{$translated_text2} <a href="<?=\$my_redirurl;?>"><?=\$my_redirurl;?></a>...</b>
300
</span>
301
<script type="text/javascript">
302
//<![CDATA[
303
LogoutWin = window.open('', 'Logout', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=256,height=64');
304
if (LogoutWin) {
305
	LogoutWin.document.write('<html>');
306
	LogoutWin.document.write('<head><title>{$translated_text3}</title></head>') ;
307
	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
	LogoutWin.document.write('<b>{$translated_text4}</b><p />');
310
	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
	LogoutWin.document.write('<input name="logout" type="submit" value="{$translated_text3}" />');
314
	LogoutWin.document.write('</form>');
315
	LogoutWin.document.write('</div></body>');
316
	LogoutWin.document.write('</html>');
317
	LogoutWin.document.close();
318
}
319

    
320
document.location.href="<?=\$my_redirurl;?>";
321
//]]>
322
</script>
323
</body>
324
</html>
325

    
326
EOD;
327
		}
328

    
329
		$fd = @fopen("{$g['varetc_path']}/captiveportal-{$cpzone}-logout.html", "w");
330
		if ($fd) {
331
			fwrite($fd, $logouttext);
332
			fclose($fd);
333
		}
334
		unset($logouttext);
335

    
336
		/* write elements */
337
		captiveportal_write_elements();
338

    
339
		/* kill any running CP nginx instances */
340
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal.pid");
341
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal-SSL.pid");
342

    
343
		/* start up the webserving daemon */
344
		captiveportal_init_webgui_zone($cpcfg);
345

    
346
		/* Kill any existing prunecaptiveportal processes */
347
		if (file_exists("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid")) {
348
			killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
349
		}
350

    
351
		/* start pruning process (interval defaults to 60 seconds) */
352
		mwexec("/usr/local/bin/minicron $croninterval {$g['varrun_path']}/cp_prunedb_{$cpzone}.pid " .
353
			"/etc/rc.prunecaptiveportal {$cpzone}");
354

    
355
		/* generate radius server database */
356
		unlink_if_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db");
357
		captiveportal_init_radius_servers();
358

    
359
		if (platform_booting()) {
360
			/* send Accounting-On to server */
361
			captiveportal_send_server_accounting();
362
			echo "done\n";
363
		}
364

    
365
	} else {
366
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal.pid");
367
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal-SSL.pid");
368
		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

    
373
		captiveportal_radius_stop_all();
374

    
375
		/* send Accounting-Off to server */
376
		if (!platform_booting()) {
377
			captiveportal_send_server_accounting(true);
378
		}
379

    
380
		/* remove old information */
381
		unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
382
		unlink_if_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db");
383
		unlink_if_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules");
384
		/* Release allocated pipes for this zone */
385
		captiveportal_free_dnrules();
386

    
387
		mwexec("/sbin/ipfw zone {$cpzoneid} destroy", true);
388

    
389
		if (empty($config['captiveportal'])) {
390
			set_single_sysctl("net.link.ether.ipfw", "0");
391
		} else {
392
			/* Deactivate ipfw(4) if not needed */
393
			$cpactive = false;
394
			if (is_array($config['captiveportal'])) {
395
				foreach ($config['captiveportal'] as $cpkey => $cp) {
396
					if (isset($cp['enable'])) {
397
						$cpactive = true;
398
						break;
399
					}
400
				}
401
			}
402
			if ($cpactive === false) {
403
				set_single_sysctl("net.link.ether.ipfw", "0");
404
			}
405
		}
406
	}
407

    
408
	unlock($captiveportallck);
409

    
410
	return 0;
411
}
412

    
413
function captiveportal_init_webgui() {
414
	global $config, $cpzone;
415

    
416
	if (is_array($config['captiveportal'])) {
417
		foreach ($config['captiveportal'] as $cpkey => $cp) {
418
			$cpzone = $cpkey;
419
			captiveportal_init_webgui_zone($cp);
420
		}
421
	}
422
}
423

    
424
function captiveportal_init_webgui_zonename($zone) {
425
	global $config, $cpzone;
426

    
427
	if (isset($config['captiveportal'][$zone])) {
428
		$cpzone = $zone;
429
		captiveportal_init_webgui_zone($config['captiveportal'][$zone]);
430
	}
431
}
432

    
433
function captiveportal_init_webgui_zone($cpcfg) {
434
	global $g, $config, $cpzone;
435

    
436
	if (!isset($cpcfg['enable'])) {
437
		return;
438
	}
439

    
440
	if (isset($cpcfg['httpslogin'])) {
441
		$cert = lookup_cert($cpcfg['certref']);
442
		$crt = base64_decode($cert['crt']);
443
		$key = base64_decode($cert['prv']);
444
		$ca = ca_chain($cert);
445

    
446
		/* generate nginx configuration */
447
		if (!empty($cpcfg['listenporthttps'])) {
448
			$listenporthttps = $cpcfg['listenporthttps'];
449
		} else {
450
			$listenporthttps = 8001 + $cpcfg['zoneid'];
451
		}
452
		system_generate_nginx_config("{$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal-SSL.conf",
453
			$crt, $key, $ca, "nginx-{$cpzone}-CaptivePortal-SSL.pid", $listenporthttps, "/usr/local/captiveportal",
454
			"cert-{$cpzone}-portal.pem", "ca-{$cpzone}-portal.pem", $cpzone);
455
	}
456

    
457
	/* generate nginx configuration */
458
	if (!empty($cpcfg['listenporthttp'])) {
459
		$listenporthttp = $cpcfg['listenporthttp'];
460
	} else {
461
		$listenporthttp = 8000 + $cpcfg['zoneid'];
462
	}
463
	system_generate_nginx_config("{$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal.conf",
464
		"", "", "", "nginx-{$cpzone}-CaptivePortal.pid", $listenporthttp, "/usr/local/captiveportal",
465
		"", "", $cpzone);
466

    
467
	@unlink("{$g['varrun']}/nginx-{$cpzone}-CaptivePortal.pid");
468
	/* attempt to start nginx */
469
	$res = mwexec("/usr/local/sbin/nginx -c {$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal.conf");
470

    
471
	/* fire up https instance */
472
	if (isset($cpcfg['httpslogin'])) {
473
		@unlink("{$g['varrun']}/nginx-{$cpzone}-CaptivePortal-SSL.pid");
474
		$res = mwexec("/usr/local/sbin/nginx -c {$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal-SSL.conf");
475
	}
476
}
477

    
478
function captiveportal_init_rules_byinterface($interface) {
479
	global $cpzone, $cpzoneid, $config;
480

    
481
	if (!is_array($config['captiveportal'])) {
482
		return;
483
	}
484

    
485
	foreach ($config['captiveportal'] as $cpkey => $cp) {
486
		$cpzone = $cpkey;
487
		$cpzoneid = $cp['zoneid'];
488
		$cpinterfaces = explode(",", $cp['interface']);
489
		if (in_array($interface, $cpinterfaces)) {
490
			captiveportal_init_rules();
491
			break;
492
		}
493
	}
494
}
495

    
496
/* reinit will disconnect all users, be careful! */
497
function captiveportal_init_rules($reinit = false) {
498
	global $config, $g, $cpzone, $cpzoneid;
499

    
500
	if (!isset($config['captiveportal'][$cpzone]['enable'])) {
501
		return;
502
	}
503

    
504
	captiveportal_load_modules();
505
	mwexec("/sbin/ipfw zone {$cpzoneid} create", true);
506

    
507
	/* Cleanup so nothing is leaked */
508
	captiveportal_free_dnrules();
509
	unlink_if_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules");
510

    
511
	$cpips = array();
512
	$ifaces = get_configured_interface_list();
513
	$cpinterfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
514
	$firsttime = 0;
515
	foreach ($cpinterfaces as $cpifgrp) {
516
		if (!isset($ifaces[$cpifgrp])) {
517
			continue;
518
		}
519
		$tmpif = get_real_interface($cpifgrp);
520
		if (!empty($tmpif)) {
521
			$cpipm = get_interface_ip($cpifgrp);
522
			if (is_ipaddr($cpipm)) {
523
				$cpips[] = $cpipm;
524
				if (is_array($config['virtualip']['vip'])) {
525
					foreach ($config['virtualip']['vip'] as $vip) {
526
						if (($vip['interface'] == $cpifgrp) && (($vip['mode'] == "carp") || ($vip['mode'] == "ipalias"))) {
527
							$cpips[] = $vip['subnet'];
528
						}
529
					}
530
				}
531
			}
532
			mwexec("/sbin/ipfw zone {$cpzoneid} madd {$tmpif}", true);
533
		}
534
	}
535
	if (count($cpips) > 0) {
536
		$cpactive = true;
537
	} else {
538
		return false;
539
	}
540

    
541
	if ($reinit == false) {
542
		$captiveportallck = lock("captiveportal{$cpzone}");
543
	}
544

    
545
	$cprules = <<<EOD
546

    
547
flush
548
add 65291 allow pfsync from any to any
549
add 65292 allow carp from any to any
550

    
551
# layer 2: pass ARP
552
add 65301 pass layer2 mac-type arp,rarp
553
# pfsense requires for WPA
554
add 65302 pass layer2 mac-type 0x888e,0x88c7
555
# PPP Over Ethernet Session Stage/Discovery Stage
556
add 65303 pass layer2 mac-type 0x8863,0x8864
557

    
558
# layer 2: block anything else non-IP(v4/v6)
559
add 65307 deny layer2 not mac-type ip,ipv6
560

    
561
EOD;
562

    
563
	$rulenum = 65310;
564
	/* These tables contain host ips */
565
	$cprules .= "add {$rulenum} pass ip from any to table(100) in\n";
566
	$rulenum++;
567
	$cprules .= "add {$rulenum} pass ip from table(100) to any out\n";
568
	$rulenum++;
569
	foreach ($cpips as $cpip) {
570
		$cprules .= "table 100 add {$cpip}\n";
571
	}
572
	$cprules .= "add {$rulenum} pass ip from any to 255.255.255.255 in\n";
573
	$rulenum++;
574
	$cprules .= "add {$rulenum} pass ip from 255.255.255.255 to any out\n";
575
	$rulenum++;
576

    
577
	/* Allowed ips */
578
	$cprules .= "add {$rulenum} pipe tablearg ip from table(3) to any in\n";
579
	$rulenum++;
580
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(4) in\n";
581
	$rulenum++;
582
	$cprules .= "add {$rulenum} pipe tablearg ip from table(3) to any out\n";
583
	$rulenum++;
584
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(4) out\n";
585
	$rulenum++;
586

    
587
	/* Authenticated users rules. */
588
	$cprules .= "add {$rulenum} pipe tablearg ip from table(1) to any in\n";
589
	$rulenum++;
590
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(2) out\n";
591
	$rulenum++;
592

    
593
	if (!empty($config['captiveportal'][$cpzone]['listenporthttp'])) {
594
		$listenporthttp = $config['captiveportal'][$cpzone]['listenporthttp'];
595
	} else {
596
		$listenporthttp = 8000 + $cpzoneid;
597
	}
598

    
599
	if (isset($config['captiveportal'][$cpzone]['httpslogin'])) {
600
		if (!empty($config['captiveportal'][$cpzone]['listenporthttps'])) {
601
			$listenporthttps = $config['captiveportal'][$cpzone]['listenporthttps'];
602
		} else {
603
			$listenporthttps = 8001 + $cpzoneid;
604
		}
605
		if (!isset($config['captiveportal'][$cpzone]['nohttpsforwards'])) {
606
			$cprules .= "add 65531 fwd 127.0.0.1,{$listenporthttps} tcp from any to any dst-port 443 in\n";
607
		}
608
	}
609

    
610
	$cprules .= <<<EOD
611

    
612
# redirect non-authenticated clients to captive portal
613
add 65532 fwd 127.0.0.1,{$listenporthttp} tcp from any to any dst-port 80 in
614
# let the responses from the captive portal web server back out
615
add 65533 pass tcp from any to any out
616
# block everything else
617
add 65534 deny all from any to any
618

    
619
EOD;
620

    
621
	/* generate passthru mac database */
622
	$cprules .= captiveportal_passthrumac_configure(true);
623
	$cprules .= "\n";
624

    
625
	/* allowed ipfw rules to make allowed ip work */
626
	$cprules .= captiveportal_allowedip_configure();
627

    
628
	/* allowed ipfw rules to make allowed hostnames work */
629
	$cprules .= captiveportal_allowedhostname_configure();
630

    
631
	/* load rules */
632
	file_put_contents("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules", $cprules);
633
	mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/ipfw_{$cpzone}.cp.rules", true);
634
	//@unlink("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules");
635
	unset($cprules);
636

    
637
	if ($reinit == false) {
638
		unlock($captiveportallck);
639
	}
640
}
641

    
642
/*
643
 * Remove clients that have been around for longer than the specified amount of time
644
 * db file structure:
645
 * timestamp,ipfw_rule_no,clientip,clientmac,username,sessionid,password,session_timeout,idle_timeout,session_terminate_time,interim_interval
646
 * (password is in Base64 and only saved when reauthentication is enabled)
647
 */
648
function captiveportal_prune_old() {
649
	global $g, $config, $cpzone, $cpzoneid;
650

    
651
	if (empty($cpzone)) {
652
		return;
653
	}
654

    
655
	$cpcfg = $config['captiveportal'][$cpzone];
656
	$vcpcfg = $config['voucher'][$cpzone];
657

    
658
	/* check for expired entries */
659
	$idletimeout = 0;
660
	$timeout = 0;
661
	if (!empty($cpcfg['timeout']) && is_numeric($cpcfg['timeout'])) {
662
		$timeout = $cpcfg['timeout'] * 60;
663
	}
664

    
665
	if (!empty($cpcfg['idletimeout']) && is_numeric($cpcfg['idletimeout'])) {
666
		$idletimeout = $cpcfg['idletimeout'] * 60;
667
	}
668

    
669
	/* Is there any job to do? */
670
	if (!$timeout && !$idletimeout && !isset($cpcfg['reauthenticate']) &&
671
	    !isset($cpcfg['radiussession_timeout']) && !isset($vcpcfg['enable'])) {
672
		return;
673
	}
674

    
675
	$radiussrvs = captiveportal_get_radius_servers();
676

    
677
	/* Read database */
678
	/* NOTE: while this can be simplified in non radius case keep as is for now */
679
	$cpdb = captiveportal_read_db();
680

    
681
	$unsetindexes = array();
682
	$voucher_needs_sync = false;
683
	/*
684
	 * Snapshot the time here to use for calculation to speed up the process.
685
	 * If something is missed next run will catch it!
686
	 */
687
	$pruning_time = time();
688
	foreach ($cpdb as $cpentry) {
689
		$stop_time = $pruning_time;
690

    
691
		$timedout = false;
692
		$term_cause = 1;
693
		if (empty($cpentry[11])) {
694
			$cpentry[11] = 'first';
695
		}
696
		$radiusservers = $radiussrvs[$cpentry[11]];
697

    
698
		/* hard timeout? */
699
		if ($timeout) {
700
			if (($pruning_time - $cpentry[0]) >= $timeout) {
701
				$timedout = true;
702
				$term_cause = 5; // Session-Timeout
703
			}
704
		}
705

    
706
		/* Session-Terminate-Time */
707
		if (!$timedout && !empty($cpentry[9])) {
708
			if ($pruning_time >= $cpentry[9]) {
709
				$timedout = true;
710
				$term_cause = 5; // Session-Timeout
711
			}
712
		}
713

    
714
		/* check if the radius idle_timeout attribute has been set and if its set change the idletimeout to this value */
715
		$uidletimeout = (is_numeric($cpentry[8])) ? $cpentry[8] : $idletimeout;
716
		/* if an idle timeout is specified, get last activity timestamp from ipfw */
717
		if (!$timedout && $uidletimeout > 0) {
718
			$lastact = captiveportal_get_last_activity($cpentry[2], $cpentry[3]);
719
			/*	If the user has logged on but not sent any traffic they will never be logged out.
720
			 *	We "fix" this by setting lastact to the login timestamp.
721
			 */
722
			$lastact = $lastact ? $lastact : $cpentry[0];
723
			if ($lastact && (($pruning_time - $lastact) >= $uidletimeout)) {
724
				$timedout = true;
725
				$term_cause = 4; // Idle-Timeout
726
				$stop_time = $lastact; // Entry added to comply with WISPr
727
			}
728
		}
729

    
730
		/* if vouchers are configured, activate session timeouts */
731
		if (!$timedout && isset($vcpcfg['enable']) && !empty($cpentry[7])) {
732
			if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
733
				$timedout = true;
734
				$term_cause = 5; // Session-Timeout
735
				$voucher_needs_sync = true;
736
			}
737
		}
738

    
739
		/* if radius session_timeout is enabled and the session_timeout is not null, then check if the user should be logged out */
740
		if (!$timedout && isset($cpcfg['radiussession_timeout']) && !empty($cpentry[7])) {
741
			if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
742
				$timedout = true;
743
				$term_cause = 5; // Session-Timeout
744
			}
745
		}
746

    
747
		if ($timedout) {
748
			captiveportal_disconnect($cpentry, $radiusservers, $term_cause, $stop_time);
749
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "TIMEOUT");
750
			$unsetindexes[] = $cpentry[5];
751
		}
752

    
753
		/* do periodic RADIUS reauthentication? */
754
		if (!$timedout && !empty($radiusservers)) {
755
			if (isset($cpcfg['radacct_enable'])) {
756
				if (substr($cpcfg['reauthenticateacct'], 0, 9) == "stopstart") {
757
					/* stop and restart accounting */
758
					if ($cpcfg['reauthenticateacct'] == "stopstartfreeradius") {
759
						$rastart_time = 0;
760
						$rastop_time = 60;
761
					} else {
762
						$rastart_time = $cpentry[0];
763
						$rastop_time = null;
764
					}
765
					RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
766
						$cpentry[4], // username
767
						$cpentry[5], // sessionid
768
						$rastart_time, // start time
769
						$radiusservers,
770
						$cpentry[2], // clientip
771
						$cpentry[3], // clientmac
772
						10, // NAS Request
773
						false, // Not an interim request
774
						$rastop_time); // Stop Time
775
					$clientsn = (is_ipaddrv6($cpentry[2])) ? 128 : 32;
776
					$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XZEROENTRY, 1, $cpentry[2], $clientsn, $cpentry[3]);
777
					$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XZEROENTRY, 2, $cpentry[2], $clientsn, $cpentry[3]);
778
					if ($cpcfg['reauthenticateacct'] == "stopstartfreeradius") {
779
						/* Need to pause here or the FreeRADIUS server gets confused about packet ordering. */
780
						sleep(1);
781
					}
782
					RADIUS_ACCOUNTING_START($cpentry[1], // ruleno
783
						$cpentry[4], // username
784
						$cpentry[5], // sessionid
785
						$radiusservers,
786
						$cpentry[2], // clientip
787
						$cpentry[3]); // clientmac
788
				} else if ($cpcfg['reauthenticateacct'] == "interimupdate") {
789
					$session_time = $pruning_time - $cpentry[0];
790
					if (!empty($cpentry[10]) && $cpentry[10] > 60) {
791
						$interval = $cpentry[10];
792
					} else {
793
						$interval = 0;
794
					}
795
					$past_interval_min = ($session_time > $interval);
796
					if ($interval != 0) {
797
						$within_interval = ($session_time % $interval >= 0 && $session_time % $interval <= 59);
798
					}
799
					if ($interval === 0 || ($interval > 0 && $past_interval_min && $within_interval)) {
800
						RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
801
							$cpentry[4], // username
802
							$cpentry[5], // sessionid
803
							$cpentry[0], // start time
804
							$radiusservers,
805
							$cpentry[2], // clientip
806
							$cpentry[3], // clientmac
807
							10, // NAS Request
808
							true); // Interim Updates
809
					}
810
				}
811
			}
812

    
813
			/* check this user against RADIUS again */
814
			if (isset($cpcfg['reauthenticate'])) {
815
				$auth_list = RADIUS_AUTHENTICATION($cpentry[4], // username
816
					base64_decode($cpentry[6]), // password
817
					$radiusservers,
818
					$cpentry[2], // clientip
819
					$cpentry[3], // clientmac
820
					$cpentry[1]); // ruleno
821
				if ($auth_list['auth_val'] == 3) {
822
					captiveportal_disconnect($cpentry, $radiusservers, 17);
823
					captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "RADIUS_DISCONNECT", $auth_list['reply_message']);
824
					$unsetindexes[] = $cpentry[5];
825
				} else if ($auth_list['auth_val'] == 2) {
826
					captiveportal_reapply_attributes($cpentry, $auth_list);
827
				}
828
			}
829
		}
830
	}
831
	unset($cpdb);
832

    
833
	captiveportal_prune_old_automac();
834

    
835
	if ($voucher_needs_sync == true) {
836
		/* Trigger a sync of the vouchers on config */
837
		send_event("service sync vouchers");
838
	}
839

    
840
	/* write database */
841
	if (!empty($unsetindexes)) {
842
		captiveportal_remove_entries($unsetindexes);
843
	}
844
}
845

    
846
function captiveportal_prune_old_automac() {
847
	global $g, $config, $cpzone, $cpzoneid;
848

    
849
	if (is_array($config['captiveportal'][$cpzone]['passthrumac']) && isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
850
		$tmpvoucherdb = array();
851
		$macrules = "";
852
		$writecfg = false;
853
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $eid => $emac) {
854
			if ($emac['logintype'] == "voucher") {
855
				if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
856
					if (isset($tmpvoucherdb[$emac['username']])) {
857
						$temac = $config['captiveportal'][$cpzone]['passthrumac'][$tmpvoucherdb[$emac['username']]];
858
						$ruleno = captiveportal_get_ipfw_passthru_ruleno($temac['mac']);
859
						$pipeno = captiveportal_get_dn_passthru_ruleno($temac['mac']);
860
						if ($ruleno) {
861
							captiveportal_free_ipfw_ruleno($ruleno);
862
							$macrules .= "delete {$ruleno}";
863
							++$ruleno;
864
							$macrules .= "delete {$ruleno}";
865
						}
866
						if ($pipeno) {
867
							captiveportal_free_dn_ruleno($pipeno);
868
							$macrules .= "pipe delete {$pipeno}\n";
869
							++$pipeno;
870
							$macrules .= "pipe delete {$pipeno}\n";
871
						}
872
						$writecfg = true;
873
						captiveportal_logportalauth($temac['username'], $temac['mac'], $temac['ip'], "DUPLICATE {$temac['username']} LOGIN - TERMINATING OLD SESSION");
874
						unset($config['captiveportal'][$cpzone]['passthrumac'][$tmpvoucherdb[$emac['username']]]);
875
					}
876
					$tmpvoucherdb[$emac['username']] = $eid;
877
				}
878
				if (voucher_auth($emac['username']) <= 0) {
879
					$ruleno = captiveportal_get_ipfw_passthru_ruleno($emac['mac']);
880
					$pipeno = captiveportal_get_dn_passthru_ruleno($emac['mac']);
881
					if ($ruleno) {
882
						captiveportal_free_ipfw_ruleno($ruleno);
883
						$macrules .= "delete {$ruleno}";
884
						++$ruleno;
885
						$macrules .= "delete {$ruleno}";
886
					}
887
					if ($pipeno) {
888
						captiveportal_free_dn_ruleno($pipeno);
889
						$macrules .= "pipe delete {$pipeno}\n";
890
						++$pipeno;
891
						$macrules .= "pipe delete {$pipeno}\n";
892
					}
893
					$writecfg = true;
894
					captiveportal_logportalauth($emac['username'], $emac['mac'], $emac['ip'], "EXPIRED {$emac['username']} LOGIN - TERMINATING SESSION");
895
					unset($config['captiveportal'][$cpzone]['passthrumac'][$eid]);
896
				}
897
			}
898
		}
899
		unset($tmpvoucherdb);
900
		if (!empty($macrules)) {
901
			@file_put_contents("{$g['tmp_path']}/macentry.prunerules.tmp", $macrules);
902
			unset($macrules);
903
			mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/macentry.prunerules.tmp");
904
		}
905
		if ($writecfg === true) {
906
			write_config("Prune session for auto-added macs");
907
		}
908
	}
909
}
910

    
911
/* remove a single client according to the DB entry */
912
function captiveportal_disconnect($dbent, $radiusservers, $term_cause = 1, $stop_time = null) {
913
	global $g, $config, $cpzone, $cpzoneid;
914

    
915
	$stop_time = (empty($stop_time)) ? time() : $stop_time;
916

    
917
	/* this client needs to be deleted - remove ipfw rules */
918
	if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers)) {
919
		if ($config['captiveportal'][$cpzone]['reauthenticateacct'] == "stopstartfreeradius") {
920
			/* Interim updates are on so the session time must be reported as the elapsed time since the previous interim update. */
921
			$session_time = ($stop_time - $dbent[0]) % 60;
922
			$start_time = $stop_time - $session_time;
923
		} else {
924
			$start_time = $dbent[0];
925
		}
926
		RADIUS_ACCOUNTING_STOP($dbent[1], // ruleno
927
			$dbent[4], // username
928
			$dbent[5], // sessionid
929
			$start_time, // start time
930
			$radiusservers,
931
			$dbent[2], // clientip
932
			$dbent[3], // clientmac
933
			$term_cause, // Acct-Terminate-Cause
934
			false,
935
			$stop_time);
936
	}
937

    
938
	if (is_ipaddr($dbent[2])) {
939
		/* Delete client's ip entry from tables 1 and 2. */
940
		$clientsn = (is_ipaddrv6($dbent[2])) ? 128 : 32;
941
		pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XDEL, 1, $dbent[2], $clientsn, $dbent[3]);
942
		pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XDEL, 2, $dbent[2], $clientsn, $dbent[3]);
943
		/* XXX: Redundant?! Ensure all pf(4) states are killed. */
944
		$_gb = @pfSense_kill_states($dbent[2]);
945
		$_gb = @pfSense_kill_srcstates($dbent[2]);
946
	}
947

    
948
	/*
949
	* These are the pipe numbers we use to control traffic shaping for each logged in user via captive portal
950
	* We could get an error if the pipe doesn't exist but everything should still be fine
951
	*/
952
	if (!empty($dbent[1])) {
953
		$_gb = @pfSense_pipe_action("pipe delete {$dbent[1]}");
954
		$_gb = @pfSense_pipe_action("pipe delete " . ($dbent[1]+1));
955

    
956
		/* Release the ruleno so it can be reallocated to new clients. */
957
		captiveportal_free_dn_ruleno($dbent[1]);
958
	}
959

    
960
	// XMLRPC Call over to the master Voucher node
961
	if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) {
962
		$syncip   = $config['voucher'][$cpzone]['vouchersyncdbip'];
963
		$syncport = $config['voucher'][$cpzone]['vouchersyncport'];
964
		$syncpass = $config['voucher'][$cpzone]['vouchersyncpass'];
965
		$vouchersyncusername = $config['voucher'][$cpzone]['vouchersyncusername'];
966
		$remote_status = xmlrpc_sync_voucher_disconnect($dbent, $syncip, $syncport, $syncpass, $vouchersyncusername, $term_cause, $stop_time);
967
	}
968

    
969
}
970

    
971
/* remove a single client by sessionid */
972
function captiveportal_disconnect_client($sessionid, $term_cause = 1, $logoutReason = "LOGOUT") {
973
	global $g, $config;
974

    
975
	$sessionid = SQLite3::escapeString($sessionid);
976
	$radiusservers = captiveportal_get_radius_servers();
977

    
978
	/* read database */
979
	$result = captiveportal_read_db("WHERE sessionid = '{$sessionid}'");
980

    
981
	/* find entry */
982
	if (!empty($result)) {
983
		captiveportal_write_db("DELETE FROM captiveportal WHERE sessionid = '{$sessionid}'");
984

    
985
		foreach ($result as $cpentry) {
986
			if (empty($cpentry[11])) {
987
				$cpentry[11] = 'first';
988
			}
989
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], $term_cause);
990
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "DISCONNECT");
991
		}
992
		unset($result);
993
	}
994
}
995

    
996
/* send RADIUS acct stop for all current clients */
997
function captiveportal_radius_stop_all() {
998
	global $config, $cpzone;
999

    
1000
	if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
1001
		return;
1002
	}
1003

    
1004
	$radiusservers = captiveportal_get_radius_servers();
1005
	if (!empty($radiusservers)) {
1006
		$cpdb = captiveportal_read_db();
1007
		foreach ($cpdb as $cpentry) {
1008
			if (empty($cpentry[11])) {
1009
				$cpentry[11] = 'first';
1010
			}
1011
			if (!empty($radiusservers[$cpentry[11]])) {
1012
				RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
1013
					$cpentry[4], // username
1014
					$cpentry[5], // sessionid
1015
					$cpentry[0], // start time
1016
					$radiusservers[$cpentry[11]],
1017
					$cpentry[2], // clientip
1018
					$cpentry[3], // clientmac
1019
					7); // Admin Reboot
1020
			}
1021
		}
1022
	}
1023
}
1024

    
1025
function captiveportal_passthrumac_configure_entry($macent, $pipeinrule = false) {
1026
	global $config, $g, $cpzone;
1027

    
1028
	$bwUp = 0;
1029
	if (!empty($macent['bw_up'])) {
1030
		$bwUp = $macent['bw_up'];
1031
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1032
		$bwUp = $config['captiveportal'][$cpzone]['bwdefaultup'];
1033
	}
1034
	$bwDown = 0;
1035
	if (!empty($macent['bw_down'])) {
1036
		$bwDown = $macent['bw_down'];
1037
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1038
		$bwDown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1039
	}
1040

    
1041
	$ruleno = captiveportal_get_next_ipfw_ruleno();
1042

    
1043
	if ($macent['action'] == 'pass') {
1044
		$rules = "";
1045
		$pipeno = captiveportal_get_next_dn_ruleno();
1046

    
1047
		$pipeup = $pipeno;
1048
		if ($pipeinrule == true) {
1049
			$_gb = @pfSense_pipe_action("pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16");
1050
		} else {
1051
			$rules .= "pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16\n";
1052
		}
1053

    
1054
		$pipedown = $pipeno + 1;
1055
		if ($pipeinrule == true) {
1056
			$_gb = @pfSense_pipe_action("pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16");
1057
		} else {
1058
			$rules .= "pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16\n";
1059
		}
1060

    
1061
		$rules .= "add {$ruleno} pipe {$pipeup} ip from any to any MAC any {$macent['mac']}\n";
1062
		$ruleno++;
1063
		$rules .= "add {$ruleno} pipe {$pipedown} ip from any to any MAC {$macent['mac']} any\n";
1064
	}
1065

    
1066
	return $rules;
1067
}
1068

    
1069
function captiveportal_passthrumac_delete_entry($macent) {
1070
	$rules = "";
1071

    
1072
	if ($macent['action'] == 'pass') {
1073
		$ruleno = captiveportal_get_ipfw_passthru_ruleno($macent['mac']);
1074

    
1075
		if (!$ruleno) {
1076
			return $rules;
1077
		}
1078

    
1079
		captiveportal_free_ipfw_ruleno($ruleno);
1080

    
1081
		$rules .= "delete {$ruleno}\n";
1082
		$rules .= "delete " . ++$ruleno . "\n";
1083

    
1084
		$pipeno = captiveportal_get_dn_passthru_ruleno($macent['mac']);
1085

    
1086
		if (!empty($pipeno)) {
1087
			captiveportal_free_dn_ruleno($pipeno);
1088
			$rules .= "pipe delete " . $pipeno . "\n";
1089
			$rules .= "pipe delete " . ++$pipeno . "\n";
1090
		}
1091
	}
1092

    
1093
	return $rules;
1094
}
1095

    
1096
function captiveportal_passthrumac_configure($filename = false, $startindex = 0, $stopindex = 0) {
1097
	global $config, $g, $cpzone;
1098

    
1099
	$rules = "";
1100

    
1101
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1102
		if ($stopindex > 0) {
1103
			$fd = fopen($filename, "w");
1104
			for ($idx = $startindex; $idx <= $stopindex; $idx++) {
1105
				if (isset($config['captiveportal'][$cpzone]['passthrumac'][$idx])) {
1106
					$rules = captiveportal_passthrumac_configure_entry($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
1107
					fwrite($fd, $rules);
1108
				}
1109
			}
1110
			fclose($fd);
1111

    
1112
			return;
1113
		} else {
1114
			$nentries = count($config['captiveportal'][$cpzone]['passthrumac']);
1115
			if ($nentries > 2000) {
1116
				$nloops = $nentries / 1000;
1117
				$remainder= $nentries % 1000;
1118
				for ($i = 0; $i < $nloops; $i++) {
1119
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . ((($i+1) * 1000) - 1) . "\"");
1120
				}
1121
				if ($remainder > 0) {
1122
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . (($i* 1000) + $remainder) ."\"");
1123
				}
1124
			} else {
1125
				foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1126
					$rules .= captiveportal_passthrumac_configure_entry($macent, true);
1127
				}
1128
			}
1129
		}
1130
	}
1131

    
1132
	return $rules;
1133
}
1134

    
1135
function captiveportal_passthrumac_findbyname($username) {
1136
	global $config, $cpzone;
1137

    
1138
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1139
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1140
			if ($macent['username'] == $username) {
1141
				return $macent;
1142
			}
1143
		}
1144
	}
1145
	return NULL;
1146
}
1147

    
1148
/*
1149
 * table (3=IN)/(4=OUT) hold allowed ip's without bw limits
1150
 */
1151
function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) {
1152
	global $g;
1153

    
1154
	/*  Instead of copying this entire function for something
1155
	 *  easy such as hostname vs ip address add this check
1156
	 */
1157
	if ($ishostname === true) {
1158
		if (!platform_booting()) {
1159
			$ipaddress = gethostbyname($ipent['hostname']);
1160
			if (!is_ipaddr($ipaddress)) {
1161
				return;
1162
			}
1163
		} else {
1164
			$ipaddress = "";
1165
		}
1166
	} else {
1167
		$ipaddress = $ipent['ip'];
1168
	}
1169

    
1170
	$rules = "";
1171
	$cp_filterdns_conf = "";
1172
	$enBwup = 0;
1173
	if (!empty($ipent['bw_up'])) {
1174
		$enBwup = intval($ipent['bw_up']);
1175
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1176
		$enBwup = $config['captiveportal'][$cpzone]['bwdefaultup'];
1177
	}
1178
	$enBwdown = 0;
1179
	if (!empty($ipent['bw_down'])) {
1180
		$enBwdown = intval($ipent['bw_down']);
1181
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1182
		$enBwdown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1183
	}
1184

    
1185
	$pipeno = captiveportal_get_next_dn_ruleno();
1186
	$_gb = @pfSense_pipe_action("pipe {$pipeno} config bw {$enBwup}Kbit/s queue 100 buckets 16");
1187
	$pipedown = $pipeno + 1;
1188
	$_gb = @pfSense_pipe_action("pipe {$pipedown} config bw {$enBwdown}Kbit/s queue 100 buckets 16");
1189
	if ($ishostname === true) {
1190
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} 3 pipe {$pipeno}\n";
1191
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} 4 pipe {$pipedown}\n";
1192
		if (!is_ipaddr($ipaddress)) {
1193
			return array("", $cp_filterdns_conf);
1194
		}
1195
	}
1196
	$subnet = "";
1197
	if (!empty($ipent['sn'])) {
1198
		$subnet = "/{$ipent['sn']}";
1199
	}
1200
	$rules .= "table 3 add {$ipaddress}{$subnet} {$pipeno}\n";
1201
	$rules .= "table 4 add {$ipaddress}{$subnet} {$pipedown}\n";
1202

    
1203
	if ($ishostname === true) {
1204
		return array($rules, $cp_filterdns_conf);
1205
	} else {
1206
		return $rules;
1207
	}
1208
}
1209

    
1210
function captiveportal_allowedhostname_configure() {
1211
	global $config, $g, $cpzone, $cpzoneid;
1212

    
1213
	$rules = "";
1214
	if (is_array($config['captiveportal'][$cpzone]['allowedhostname'])) {
1215
		$rules = "\n# captiveportal_allowedhostname_configure()\n";
1216
		$cp_filterdns_conf = "";
1217
		foreach ($config['captiveportal'][$cpzone]['allowedhostname'] as $hostnameent) {
1218
			$tmprules = captiveportal_allowedip_configure_entry($hostnameent, true);
1219
			$rules .= $tmprules[0];
1220
			$cp_filterdns_conf .= $tmprules[1];
1221
		}
1222
		$cp_filterdns_filename = "{$g['varetc_path']}/filterdns-{$cpzone}-captiveportal.conf";
1223
		@file_put_contents($cp_filterdns_filename, $cp_filterdns_conf);
1224
		unset($cp_filterdns_conf);
1225
		if (isvalidpid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid")) {
1226
			sigkillbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid", "HUP");
1227
		} else {
1228
			mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid -i 300 -c {$cp_filterdns_filename} -y {$cpzoneid} -d 1");
1229
		}
1230
	} else {
1231
		killbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1232
		@unlink("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1233
	}
1234

    
1235
	return $rules;
1236
}
1237

    
1238
function captiveportal_allowedip_configure() {
1239
	global $config, $g, $cpzone;
1240

    
1241
	$rules = "";
1242
	if (is_array($config['captiveportal'][$cpzone]['allowedip'])) {
1243
		foreach ($config['captiveportal'][$cpzone]['allowedip'] as $ipent) {
1244
			$rules .= captiveportal_allowedip_configure_entry($ipent);
1245
		}
1246
	}
1247

    
1248
	return $rules;
1249
}
1250

    
1251
/* get last activity timestamp given client IP address */
1252
function captiveportal_get_last_activity($ip, $mac = NULL, $table = 1) {
1253
	global $cpzoneid;
1254

    
1255
	$ipfwoutput = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, $table, $ip, $mac);
1256
	/* Reading only from one of the tables is enough of approximation. */
1257
	if (is_array($ipfwoutput)) {
1258
		/* Workaround for #46652 */
1259
		if ($ipfwoutput['packets'] > 0) {
1260
			return $ipfwoutput['timestamp'];
1261
		} else {
1262
			return 0;
1263
		}
1264
	}
1265

    
1266
	return 0;
1267
}
1268

    
1269
function captiveportal_init_radius_servers() {
1270
	global $config, $g, $cpzone;
1271

    
1272
	/* generate radius server database */
1273
	if ($config['captiveportal'][$cpzone]['radiusip'] &&
1274
	    (!isset($config['captiveportal'][$cpzone]['auth_method']) || $config['captiveportal'][$cpzone]['auth_method'] == "radius")) {
1275
		$radiusip = $config['captiveportal'][$cpzone]['radiusip'];
1276
		$radiusip2 = ($config['captiveportal'][$cpzone]['radiusip2']) ? $config['captiveportal'][$cpzone]['radiusip2'] : null;
1277
		$radiusip3 = ($config['captiveportal'][$cpzone]['radiusip3']) ? $config['captiveportal'][$cpzone]['radiusip3'] : null;
1278
		$radiusip4 = ($config['captiveportal'][$cpzone]['radiusip4']) ? $config['captiveportal'][$cpzone]['radiusip4'] : null;
1279

    
1280
		if ($config['captiveportal'][$cpzone]['radiusport']) {
1281
			$radiusport = $config['captiveportal'][$cpzone]['radiusport'];
1282
		} else {
1283
			$radiusport = 1812;
1284
		}
1285
		if ($config['captiveportal'][$cpzone]['radiusacctport']) {
1286
			$radiusacctport = $config['captiveportal'][$cpzone]['radiusacctport'];
1287
		} else {
1288
			$radiusacctport = 1813;
1289
		}
1290
		if ($config['captiveportal'][$cpzone]['radiusport2']) {
1291
			$radiusport2 = $config['captiveportal'][$cpzone]['radiusport2'];
1292
		} else {
1293
			$radiusport2 = 1812;
1294
		}
1295
		if ($config['captiveportal'][$cpzone]['radiusport3']) {
1296
			$radiusport3 = $config['captiveportal'][$cpzone]['radiusport3'];
1297
		} else {
1298
			$radiusport3 = 1812;
1299
		}
1300
		if ($config['captiveportal'][$cpzone]['radiusport4']) {
1301
			$radiusport4 = $config['captiveportal'][$cpzone]['radiusport4'];
1302
		} else {
1303
			$radiusport4 = 1812;
1304
		}
1305

    
1306
		$radiuskey = $config['captiveportal'][$cpzone]['radiuskey'];
1307
		$radiuskey2 = $config['captiveportal'][$cpzone]['radiuskey2'];
1308
		$radiuskey3 = $config['captiveportal'][$cpzone]['radiuskey3'];
1309
		$radiuskey4 = $config['captiveportal'][$cpzone]['radiuskey4'];
1310

    
1311
		$cprdsrvlck = lock("captiveportalradius{$cpzone}", LOCK_EX);
1312
		$fd = @fopen("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db", "w");
1313
		if (!$fd) {
1314
			captiveportal_syslog("Error: cannot open RADIUS DB file in captiveportal_configure().\n");
1315
			unlock($cprdsrvlck);
1316
			return 1;
1317
		}
1318
		if (isset($radiusip)) {
1319
			fwrite($fd, $radiusip . "," . $radiusport . "," . $radiusacctport . "," . $radiuskey . ",first");
1320
		}
1321
		if (isset($radiusip2)) {
1322
			fwrite($fd, "\n" . $radiusip2 . "," . $radiusport2 . "," . $radiusacctport . "," . $radiuskey2 . ",first");
1323
		}
1324
		if (isset($radiusip3)) {
1325
			fwrite($fd, "\n" . $radiusip3 . "," . $radiusport3 . "," . $radiusacctport . "," . $radiuskey3 . ",second");
1326
		}
1327
		if (isset($radiusip4)) {
1328
			fwrite($fd, "\n" . $radiusip4 . "," . $radiusport4 . "," . $radiusacctport . "," . $radiuskey4 . ",second");
1329
		}
1330

    
1331
		fclose($fd);
1332
		unlock($cprdsrvlck);
1333
	}
1334
}
1335

    
1336
/* read RADIUS servers into array */
1337
function captiveportal_get_radius_servers() {
1338
	global $g, $cpzone;
1339

    
1340
	$cprdsrvlck = lock("captiveportalradius{$cpzone}");
1341
	if (file_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db")) {
1342
		$radiusservers = array();
1343
		$cpradiusdb = file("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db",
1344
		FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1345
		if ($cpradiusdb) {
1346
			foreach ($cpradiusdb as $cpradiusentry) {
1347
				$line = trim($cpradiusentry);
1348
				if ($line) {
1349
					$radsrv = array();
1350
					list($radsrv['ipaddr'], $radsrv['port'], $radsrv['acctport'], $radsrv['key'], $context) = explode(",", $line);
1351
				}
1352
				if (empty($context)) {
1353
					if (!is_array($radiusservers['first'])) {
1354
						$radiusservers['first'] = array();
1355
					}
1356
					$radiusservers['first'] = $radsrv;
1357
				} else {
1358
					if (!is_array($radiusservers[$context])) {
1359
						$radiusservers[$context] = array();
1360
					}
1361
					$radiusservers[$context][] = $radsrv;
1362
				}
1363
			}
1364
		}
1365
		unlock($cprdsrvlck);
1366
		return $radiusservers;
1367
	}
1368

    
1369
	unlock($cprdsrvlck);
1370
	return false;
1371
}
1372

    
1373
/* log successful captive portal authentication to syslog */
1374
/* part of this code from php.net */
1375
function captiveportal_logportalauth($user, $mac, $ip, $status, $message = null) {
1376
	// Log it
1377
	if (!$message) {
1378
		$message = "{$status}: {$user}, {$mac}, {$ip}";
1379
	} else {
1380
		$message = trim($message);
1381
		$message = "{$status}: {$user}, {$mac}, {$ip}, {$message}";
1382
	}
1383
	captiveportal_syslog($message);
1384
}
1385

    
1386
/* log simple messages to syslog */
1387
function captiveportal_syslog($message) {
1388
	global $cpzone;
1389

    
1390
	$message = trim($message);
1391
	$message = "Zone: {$cpzone} - {$message}";
1392
	openlog("logportalauth", LOG_PID, LOG_LOCAL4);
1393
	// Log it
1394
	syslog(LOG_INFO, $message);
1395
	closelog();
1396
}
1397

    
1398
function radius($username, $password, $clientip, $clientmac, $type, $radiusctx = null) {
1399
	global $g, $config, $cpzoneid;
1400

    
1401
	$pipeno = captiveportal_get_next_dn_ruleno();
1402

    
1403
	/* If the pool is empty, return appropriate message and fail authentication */
1404
	if (empty($pipeno)) {
1405
		$auth_list = array();
1406
		$auth_list['auth_val'] = 1;
1407
		$auth_list['error'] = "System reached maximum login capacity";
1408
		return $auth_list;
1409
	}
1410

    
1411
	$radiusservers = captiveportal_get_radius_servers();
1412

    
1413
	if (is_null($radiusctx)) {
1414
		$radiusctx = 'first';
1415
	}
1416

    
1417
	$auth_list = RADIUS_AUTHENTICATION($username,
1418
		$password,
1419
		$radiusservers[$radiusctx],
1420
		$clientip,
1421
		$clientmac,
1422
		$pipeno);
1423

    
1424
	if ($auth_list['auth_val'] == 2) {
1425
		captiveportal_logportalauth($username, $clientmac, $clientip, $type);
1426
		$sessionid = portal_allow($clientip,
1427
			$clientmac,
1428
			$username,
1429
			$password,
1430
			$auth_list,
1431
			$pipeno,
1432
			$radiusctx);
1433
	} else {
1434
		captiveportal_free_dn_ruleno($pipeno);
1435
	}
1436

    
1437
	return $auth_list;
1438
}
1439

    
1440
function captiveportal_opendb() {
1441
	global $g, $config, $cpzone, $cpzoneid;
1442

    
1443
	$db_path = "{$g['vardb_path']}/captiveportal{$cpzone}.db";
1444
	$createquery = "CREATE TABLE IF NOT EXISTS captiveportal (" .
1445
				"allow_time INTEGER, pipeno INTEGER, ip TEXT, mac TEXT, username TEXT, " .
1446
				"sessionid TEXT, bpassword TEXT, session_timeout INTEGER, idle_timeout INTEGER, " .
1447
				"session_terminate_time INTEGER, interim_interval INTEGER, radiusctx TEXT); " .
1448
			"CREATE UNIQUE INDEX IF NOT EXISTS idx_active ON captiveportal (sessionid, username); " .
1449
			"CREATE INDEX IF NOT EXISTS user ON captiveportal (username); " .
1450
			"CREATE INDEX IF NOT EXISTS ip ON captiveportal (ip); " .
1451
			"CREATE INDEX IF NOT EXISTS starttime ON captiveportal (allow_time)";
1452

    
1453
	try {
1454
		$DB = new SQLite3($db_path);
1455
		$DB->busyTimeout(60000);
1456
	} catch (Exception $e) {
1457
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: " . $e->getMessage() . " -- Trying again.");
1458
		unlink_if_exists($db_path);
1459
		try {
1460
			$DB = new SQLite3($db_path);
1461
			$DB->busyTimeout(60000);
1462
		} catch (Exception $e) {
1463
			captiveportal_syslog("Still could not open {$db_path} as an sqlite database for {$cpzone}. Error message: " . $e->getMessage() . " -- Remove the database file manually and ensure there is enough free space.");
1464
			return;
1465
		}
1466
	}
1467

    
1468
	if (!$DB) {
1469
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Trying again.");
1470
		unlink_if_exists($db_path);
1471
		$DB = new SQLite3($db_path);
1472
		$DB->busyTimeout(60000);
1473
		if (!$DB) {
1474
			captiveportal_syslog("Still could not open {$db_path} as an sqlite database for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Remove the database file manually and ensure there is enough free space.");
1475
			return;
1476
		}
1477
	}
1478

    
1479
	if (! $DB->exec($createquery)) {
1480
		captiveportal_syslog("Error during table {$cpzone} creation. Error message: {$DB->lastErrorMsg()}. Resetting and trying again.");
1481

    
1482
		/* If unable to initialize the database, reset and try again. */
1483
		$DB->close();
1484
		unset($DB);
1485
		unlink_if_exists($db_path);
1486
		$DB = new SQLite3($db_path);
1487
		$DB->busyTimeout(60000);
1488
		if ($DB->exec($createquery)) {
1489
			captiveportal_syslog("Successfully reinitialized tables for {$cpzone} -- database has been reset.");
1490
			if (!is_numericint($cpzoneid)) {
1491
				if (is_array($config['captiveportal'])) {
1492
					foreach ($config['captiveportal'] as $cpkey => $cp) {
1493
						if ($cpzone == $cpkey) {
1494
							$cpzoneid = $cp['zoneid'];
1495
						}
1496
					}
1497
				}
1498
			}
1499
			if (is_numericint($cpzoneid)) {
1500
				mwexec("/sbin/ipfw -x $cpzoneid table all flush");
1501
				captiveportal_syslog("Flushed tables for {$cpzone} after database reset.");
1502
			}
1503
		} else {
1504
			captiveportal_syslog("Still unable to create tables for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Remove the database file manually and try again.");
1505
		}
1506
	}
1507

    
1508
	return $DB;
1509
}
1510

    
1511
/* read captive portal DB into array */
1512
function captiveportal_read_db($query = "") {
1513
	$cpdb = array();
1514

    
1515
	$DB = captiveportal_opendb();
1516
	if ($DB) {
1517
		$response = $DB->query("SELECT * FROM captiveportal {$query}");
1518
		if ($response != FALSE) {
1519
			while ($row = $response->fetchArray()) {
1520
				$cpdb[] = $row;
1521
			}
1522
		}
1523
		$DB->close();
1524
	}
1525

    
1526
	return $cpdb;
1527
}
1528

    
1529
function captiveportal_remove_entries($remove) {
1530

    
1531
	if (!is_array($remove) || empty($remove)) {
1532
		return;
1533
	}
1534

    
1535
	$query = "DELETE FROM captiveportal WHERE sessionid in (";
1536
	foreach ($remove as $idx => $unindex) {
1537
		$query .= "'{$unindex}'";
1538
		if ($idx < (count($remove) - 1)) {
1539
			$query .= ",";
1540
		}
1541
	}
1542
	$query .= ")";
1543
	captiveportal_write_db($query);
1544
}
1545

    
1546
/* write captive portal DB */
1547
function captiveportal_write_db($queries) {
1548
	global $g;
1549

    
1550
	if (is_array($queries)) {
1551
		$query = implode(";", $queries);
1552
	} else {
1553
		$query = $queries;
1554
	}
1555

    
1556
	$DB = captiveportal_opendb();
1557
	if ($DB) {
1558
		$DB->exec("BEGIN TRANSACTION");
1559
		$result = $DB->exec($query);
1560
		if (!$result) {
1561
			captiveportal_syslog("Trying to modify DB returned error: {$DB->lastErrorMsg()}");
1562
		} else {
1563
			$DB->exec("END TRANSACTION");
1564
		}
1565
		$DB->close();
1566
		return $result;
1567
	} else {
1568
		return true;
1569
	}
1570
}
1571

    
1572
function captiveportal_write_elements() {
1573
	global $g, $config, $cpzone;
1574

    
1575
	$cpcfg = $config['captiveportal'][$cpzone];
1576

    
1577
	if (!is_dir($g['captiveportal_element_path'])) {
1578
		@mkdir($g['captiveportal_element_path']);
1579
	}
1580

    
1581
	if (is_array($cpcfg['element'])) {
1582
		conf_mount_rw();
1583
		foreach ($cpcfg['element'] as $data) {
1584
			/* Do not attempt to decode or write out empty files. */
1585
			if (empty($data['content']) || empty(base64_decode($data['content']))) {
1586
				unlink_if_exists("{$g['captiveportal_element_path']}/{$data['name']}");
1587
				touch("{$g['captiveportal_element_path']}/{$data['name']}");
1588
			} elseif (!@file_put_contents("{$g['captiveportal_element_path']}/{$data['name']}", base64_decode($data['content']))) {
1589
				printf(gettext("Error: cannot open '%s' in captiveportal_write_elements()%s"), $data['name'], "\n");
1590
				return 1;
1591
			}
1592
			if (!file_exists("{$g['captiveportal_path']}/{$data['name']}")) {
1593
				@symlink("{$g['captiveportal_element_path']}/{$data['name']}", "{$g['captiveportal_path']}/{$data['name']}");
1594
			}
1595
		}
1596
		conf_mount_ro();
1597
	}
1598

    
1599
	return 0;
1600
}
1601

    
1602
function captiveportal_free_dnrules($rulenos_start = 2000, $rulenos_range_max = 64500) {
1603
	global $cpzone;
1604

    
1605
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1606
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1607
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1608
		$ridx = $rulenos_start;
1609
		while ($ridx < $rulenos_range_max) {
1610
			if ($rules[$ridx] == $cpzone) {
1611
				$rules[$ridx] = false;
1612
				$ridx++;
1613
				$rules[$ridx] = false;
1614
				$ridx++;
1615
			} else {
1616
				$ridx += 2;
1617
			}
1618
		}
1619
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1620
		unset($rules);
1621
	}
1622
	unlock($cpruleslck);
1623
}
1624

    
1625
function captiveportal_get_next_dn_ruleno($rulenos_start = 2000, $rulenos_range_max = 64500) {
1626
	global $config, $g, $cpzone;
1627

    
1628
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1629
	$ruleno = 0;
1630
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1631
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1632
		$ridx = $rulenos_start;
1633
		while ($ridx < $rulenos_range_max) {
1634
			if (empty($rules[$ridx])) {
1635
				$ruleno = $ridx;
1636
				$rules[$ridx] = $cpzone;
1637
				$ridx++;
1638
				$rules[$ridx] = $cpzone;
1639
				break;
1640
			} else {
1641
				$ridx += 2;
1642
			}
1643
		}
1644
	} else {
1645
		$rules = array_pad(array(), $rulenos_range_max, false);
1646
		$ruleno = $rulenos_start;
1647
		$rules[$rulenos_start] = $cpzone;
1648
		$rulenos_start++;
1649
		$rules[$rulenos_start] = $cpzone;
1650
	}
1651
	file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1652
	unlock($cpruleslck);
1653
	unset($rules);
1654

    
1655
	return $ruleno;
1656
}
1657

    
1658
function captiveportal_free_dn_ruleno($ruleno) {
1659
	global $config, $g;
1660

    
1661
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1662
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1663
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1664
		$rules[$ruleno] = false;
1665
		$ruleno++;
1666
		$rules[$ruleno] = false;
1667
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1668
		unset($rules);
1669
	}
1670
	unlock($cpruleslck);
1671
}
1672

    
1673
function captiveportal_get_dn_passthru_ruleno($value) {
1674
	global $config, $g, $cpzone, $cpzoneid;
1675

    
1676
	$cpcfg = $config['captiveportal'][$cpzone];
1677
	if (!isset($cpcfg['enable'])) {
1678
		return NULL;
1679
	}
1680

    
1681
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1682
	$ruleno = NULL;
1683
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1684
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1685
		unset($output);
1686
		$_gb = exec("/sbin/ipfw -x {$cpzoneid} show | /usr/bin/grep " . escapeshellarg($value) . " | /usr/bin/grep -v grep | /usr/bin/awk '{print $5}' | /usr/bin/head -n 1", $output);
1687
		$ruleno = intval($output[0]);
1688
		if (!$rules[$ruleno]) {
1689
			$ruleno = NULL;
1690
		}
1691
		unset($rules);
1692
	}
1693
	unlock($cpruleslck);
1694

    
1695
	return $ruleno;
1696
}
1697

    
1698
/*
1699
 * This function will calculate the lowest free firewall ruleno
1700
 * within the range specified based on the actual logged on users
1701
 *
1702
 */
1703
function captiveportal_get_next_ipfw_ruleno($rulenos_start = 2, $rulenos_range_max = 64500) {
1704
	global $config, $g, $cpzone;
1705

    
1706
	$cpcfg = $config['captiveportal'][$cpzone];
1707
	if (!isset($cpcfg['enable'])) {
1708
		return NULL;
1709
	}
1710

    
1711
	$cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX);
1712
	$ruleno = 0;
1713
	if (file_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules")) {
1714
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules"));
1715
		$ridx = $rulenos_start;
1716
		while ($ridx < $rulenos_range_max) {
1717
			if (empty($rules[$ridx])) {
1718
				$ruleno = $ridx;
1719
				$rules[$ridx] = $cpzone;
1720
				$ridx++;
1721
				$rules[$ridx] = $cpzone;
1722
				break;
1723
			} else {
1724
				/*
1725
				 * This allows our traffic shaping pipes to be the in pipe the same as ruleno
1726
				 * and the out pipe ruleno + 1.
1727
				 */
1728
				$ridx += 2;
1729
			}
1730
		}
1731
	} else {
1732
		$rules = array_pad(array(), $rulenos_range_max, false);
1733
		$ruleno = $rulenos_start;
1734
		$rules[$rulenos_start] = $cpzone;
1735
		$rulenos_start++;
1736
		$rules[$rulenos_start] = $cpzone;
1737
	}
1738
	file_put_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules", serialize($rules));
1739
	unlock($cpruleslck);
1740
	unset($rules);
1741

    
1742
	return $ruleno;
1743
}
1744

    
1745
function captiveportal_free_ipfw_ruleno($ruleno) {
1746
	global $config, $g, $cpzone;
1747

    
1748
	$cpcfg = $config['captiveportal'][$cpzone];
1749
	if (!isset($cpcfg['enable'])) {
1750
		return NULL;
1751
	}
1752

    
1753
	$cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX);
1754
	if (file_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules")) {
1755
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules"));
1756
		$rules[$ruleno] = false;
1757
		$ruleno++;
1758
		$rules[$ruleno] = false;
1759
		file_put_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules", serialize($rules));
1760
		unset($rules);
1761
	}
1762
	unlock($cpruleslck);
1763
}
1764

    
1765
function captiveportal_get_ipfw_passthru_ruleno($value) {
1766
	global $config, $g, $cpzone, $cpzoneid;
1767

    
1768
	$cpcfg = $config['captiveportal'][$cpzone];
1769
	if (!isset($cpcfg['enable'])) {
1770
		return NULL;
1771
	}
1772

    
1773
	$cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX);
1774
	$ruleno = NULL;
1775
	if (file_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules")) {
1776
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules"));
1777
		unset($output);
1778
		$_gb = exec("/sbin/ipfw -x {$cpzoneid} show | /usr/bin/grep " . escapeshellarg($value) . " | /usr/bin/grep -v grep | /usr/bin/awk '{print $1}' | /usr/bin/head -n 1", $output);
1779
		$ruleno = intval($output[0]);
1780
		if (!$rules[$ruleno]) {
1781
			$ruleno = NULL;
1782
		}
1783
		unset($rules);
1784
	}
1785
	unlock($cpruleslck);
1786

    
1787
	return $ruleno;
1788
}
1789

    
1790
/**
1791
 * This function will calculate the traffic produced by a client
1792
 * based on its firewall rule
1793
 *
1794
 * Point of view: NAS
1795
 *
1796
 * Input means: from the client
1797
 * Output means: to the client
1798
 *
1799
 */
1800

    
1801
function getVolume($ip, $mac = NULL) {
1802
	global $config, $cpzone, $cpzoneid;
1803

    
1804
	$reverse = empty($config['captiveportal'][$cpzone]['reverseacct']) ? false : true;
1805
	$volume = array();
1806
	// Initialize vars properly, since we don't want NULL vars
1807
	$volume['input_pkts'] = $volume['input_bytes'] = $volume['output_pkts'] = $volume['output_bytes'] = 0 ;
1808

    
1809
	$ipfw = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, 1, $ip, $mac);
1810
	if (is_array($ipfw)) {
1811
		if ($reverse) {
1812
			$volume['output_pkts'] = $ipfw['packets'];
1813
			$volume['output_bytes'] = $ipfw['bytes'];
1814
		}
1815
		else {
1816
			$volume['input_pkts'] = $ipfw['packets'];
1817
			$volume['input_bytes'] = $ipfw['bytes'];
1818
		}
1819
	}
1820

    
1821
	$ipfw = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, 2, $ip, $mac);
1822
	if (is_array($ipfw)) {
1823
		if ($reverse) {
1824
			$volume['input_pkts'] = $ipfw['packets'];
1825
			$volume['input_bytes'] = $ipfw['bytes'];
1826
		}
1827
		else {
1828
			$volume['output_pkts'] = $ipfw['packets'];
1829
			$volume['output_bytes'] = $ipfw['bytes'];
1830
		}
1831
	}
1832

    
1833
	return $volume;
1834
}
1835

    
1836
/**
1837
 * Get the NAS-IP-Address based on the current wan address
1838
 *
1839
 * Use functions in interfaces.inc to find this out
1840
 *
1841
 */
1842

    
1843
function getNasIP() {
1844
	global $config, $cpzone;
1845

    
1846
	if (empty($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1847
			$nasIp = get_interface_ip();
1848
	} else {
1849
		if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1850
			$nasIp = $config['captiveportal'][$cpzone]['radiussrcip_attribute'];
1851
		} else {
1852
			$nasIp = get_interface_ip($config['captiveportal'][$cpzone]['radiussrcip_attribute']);
1853
		}
1854
	}
1855

    
1856
	if (!is_ipaddr($nasIp)) {
1857
		$nasIp = "0.0.0.0";
1858
	}
1859

    
1860
	return $nasIp;
1861
}
1862

    
1863
function portal_ip_from_client_ip($cliip) {
1864
	global $config, $cpzone;
1865

    
1866
	$isipv6 = is_ipaddrv6($cliip);
1867
	$interfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
1868
	foreach ($interfaces as $cpif) {
1869
		if ($isipv6) {
1870
			$ip = get_interface_ipv6($cpif);
1871
			$sn = get_interface_subnetv6($cpif);
1872
		} else {
1873
			$ip = get_interface_ip($cpif);
1874
			$sn = get_interface_subnet($cpif);
1875
		}
1876
		if (ip_in_subnet($cliip, "{$ip}/{$sn}")) {
1877
			return $ip;
1878
		}
1879
	}
1880

    
1881
	$inet = ($isipv6) ? '-inet6' : '-inet';
1882
	$iface = exec_command("/sbin/route -n get {$inet} {$cliip} | /usr/bin/awk '/interface/ { print \$2; };'");
1883
	$iface = trim($iface, "\n");
1884
	if (!empty($iface)) {
1885
		$ip = ($isipv6) ? find_interface_ipv6($iface) : find_interface_ip($iface);
1886
		if (is_ipaddr($ip)) {
1887
			return $ip;
1888
		}
1889
	}
1890

    
1891
	// doesn't match up to any particular interface
1892
	// so let's set the portal IP to what PHP says
1893
	// the server IP issuing the request is.
1894
	// allows same behavior as 1.2.x where IP isn't
1895
	// in the subnet of any CP interface (static routes, etc.)
1896
	// rather than forcing to DNS hostname resolution
1897
	$ip = $_SERVER['SERVER_ADDR'];
1898
	if (is_ipaddr($ip)) {
1899
		return $ip;
1900
	}
1901

    
1902
	return false;
1903
}
1904

    
1905
function portal_hostname_from_client_ip($cliip) {
1906
	global $config, $cpzone;
1907

    
1908
	$cpcfg = $config['captiveportal'][$cpzone];
1909

    
1910
	if (isset($cpcfg['httpslogin'])) {
1911
		$listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 8001);
1912
		$ourhostname = $cpcfg['httpsname'];
1913

    
1914
		if ($listenporthttps != 443) {
1915
			$ourhostname .= ":" . $listenporthttps;
1916
		}
1917
	} else {
1918
		$listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : ($cpcfg['zoneid'] + 8000);
1919
		$ifip = portal_ip_from_client_ip($cliip);
1920
		if (!$ifip) {
1921
			$ourhostname = "{$config['system']['hostname']}.{$config['system']['domain']}";
1922
		} else {
1923
			$ourhostname = (is_ipaddrv6($ifip)) ? "[{$ifip}]" : "{$ifip}";
1924
		}
1925

    
1926
		if ($listenporthttp != 80) {
1927
			$ourhostname .= ":" . $listenporthttp;
1928
		}
1929
	}
1930

    
1931
	return $ourhostname;
1932
}
1933

    
1934
/* functions move from index.php */
1935

    
1936
function portal_reply_page($redirurl, $type = null, $message = null, $clientmac = null, $clientip = null, $username = null, $password = null) {
1937
	global $g, $config, $cpzone;
1938

    
1939
	/* Get captive portal layout */
1940
	if ($type == "redir") {
1941
		header("Location: {$redirurl}");
1942
		return;
1943
	} else if ($type == "login") {
1944
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
1945
	} else {
1946
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
1947
	}
1948

    
1949
	$cpcfg = $config['captiveportal'][$cpzone];
1950

    
1951
	/* substitute the PORTAL_REDIRURL variable */
1952
	if ($cpcfg['preauthurl']) {
1953
		$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
1954
		$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
1955
	}
1956

    
1957
	/* substitute other variables */
1958
	$ourhostname = portal_hostname_from_client_ip($clientip);
1959
	$protocol = (isset($cpcfg['httpslogin'])) ? 'https://' : 'http://';
1960
	$htmltext = str_replace("\$PORTAL_ACTION\$", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
1961
	$htmltext = str_replace("#PORTAL_ACTION#", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
1962

    
1963
	$htmltext = str_replace("\$PORTAL_ZONE\$", htmlspecialchars($cpzone), $htmltext);
1964
	$htmltext = str_replace("\$PORTAL_REDIRURL\$", htmlspecialchars($redirurl), $htmltext);
1965
	$htmltext = str_replace("\$PORTAL_MESSAGE\$", htmlspecialchars($message), $htmltext);
1966
	$htmltext = str_replace("\$CLIENT_MAC\$", htmlspecialchars($clientmac), $htmltext);
1967
	$htmltext = str_replace("\$CLIENT_IP\$", htmlspecialchars($clientip), $htmltext);
1968

    
1969
	// Special handling case for captive portal master page so that it can be ran
1970
	// through the PHP interpreter using the include method above.  We convert the
1971
	// $VARIABLE$ case to #VARIABLE# in /etc/inc/captiveportal.inc before writing out.
1972
	$htmltext = str_replace("#PORTAL_ZONE#", htmlspecialchars($cpzone), $htmltext);
1973
	$htmltext = str_replace("#PORTAL_REDIRURL#", htmlspecialchars($redirurl), $htmltext);
1974
	$htmltext = str_replace("#PORTAL_MESSAGE#", htmlspecialchars($message), $htmltext);
1975
	$htmltext = str_replace("#CLIENT_MAC#", htmlspecialchars($clientmac), $htmltext);
1976
	$htmltext = str_replace("#CLIENT_IP#", htmlspecialchars($clientip), $htmltext);
1977
	$htmltext = str_replace("#USERNAME#", htmlspecialchars($username), $htmltext);
1978
	$htmltext = str_replace("#PASSWORD#", htmlspecialchars($password), $htmltext);
1979

    
1980
	echo $htmltext;
1981
}
1982

    
1983
function portal_mac_radius($clientmac, $clientip) {
1984
	global $config, $cpzone;
1985

    
1986
	$radmac_secret = $config['captiveportal'][$cpzone]['radmac_secret'];
1987

    
1988
	/* authentication against the radius server */
1989
	$username = mac_format($clientmac);
1990
	$auth_list = radius($username, $radmac_secret, $clientip, $clientmac, "MACHINE LOGIN");
1991
	if ($auth_list['auth_val'] == 2) {
1992
		return TRUE;
1993
	}
1994

    
1995
	if (!empty($auth_list['url_redirection'])) {
1996
		portal_reply_page($auth_list['url_redirection'], "redir");
1997
	}
1998

    
1999
	return FALSE;
2000
}
2001

    
2002
function captiveportal_reapply_attributes($cpentry, $attributes) {
2003
	global $config, $cpzone, $g;
2004

    
2005
	if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2006
		$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2007
		$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2008
	} else {
2009
		$dwfaultbw_up = $dwfaultbw_down = 0;
2010
	}
2011
	$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2012
	$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2013
	$bw_up_pipeno = $cpentry[1];
2014
	$bw_down_pipeno = $cpentry[1]+1;
2015

    
2016
	$_gb = @pfSense_pipe_action("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2017
	$_gb = @pfSense_pipe_action("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2018
	//captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "RADIUS_BANDWIDTH_REAPPLY", "{$bw_up}/{$bw_down}");
2019

    
2020
	unset($bw_up_pipeno, $bw_down_pipeno, $bw_up, $bw_down);
2021
}
2022

    
2023
function portal_allow($clientip, $clientmac, $username, $password = null, $attributes = null, $pipeno = null, $radiusctx = null) {
2024
	global $redirurl, $g, $config, $type, $passthrumac, $_POST, $cpzone, $cpzoneid;
2025

    
2026
	// Ensure we create an array if we are missing attributes
2027
	if (!is_array($attributes)) {
2028
		$attributes = array();
2029
	}
2030

    
2031
	unset($sessionid);
2032

    
2033
	/* Do not allow concurrent login execution. */
2034
	$cpdblck = lock("captiveportaldb{$cpzone}", LOCK_EX);
2035

    
2036
	if ($attributes['voucher']) {
2037
		$remaining_time = $attributes['session_timeout'];
2038
	// Set RADIUS-Attribute to Voucher to prevent ReAuth-Reqeuest for Vouchers Bug: #2155
2039
		$radiusctx="voucher";
2040
	}
2041

    
2042
	$writecfg = false;
2043
	/* Find an existing session */
2044
	if ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && $passthrumac) {
2045
		if (isset($config['captiveportal'][$cpzone]['passthrumacadd'])) {
2046
			$mac = captiveportal_passthrumac_findbyname($username);
2047
			if (!empty($mac)) {
2048
				if ($_POST['replacemacpassthru']) {
2049
					foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $idx => $macent) {
2050
						if ($macent['mac'] == $mac['mac']) {
2051
							$macrules = "";
2052
							$ruleno = captiveportal_get_ipfw_passthru_ruleno($mac['mac']);
2053
							$pipeno = captiveportal_get_dn_passthru_ruleno($mac['mac']);
2054
							if ($ruleno) {
2055
								captiveportal_free_ipfw_ruleno($ruleno);
2056
								$macrules .= "delete {$ruleno}\n";
2057
								++$ruleno;
2058
								$macrules .= "delete {$ruleno}\n";
2059
							}
2060
							if ($pipeno) {
2061
								captiveportal_free_dn_ruleno($pipeno);
2062
								$macrules .= "pipe delete {$pipeno}\n";
2063
								++$pipeno;
2064
								$macrules .= "pipe delete {$pipeno}\n";
2065
							}
2066
							unset($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
2067
							$mac['action'] = 'pass';
2068
							$mac['mac'] = $clientmac;
2069
							$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2070
							$macrules .= captiveportal_passthrumac_configure_entry($mac);
2071
							file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2072
							mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2073
							$writecfg = true;
2074
							$sessionid = true;
2075
							break;
2076
						}
2077
					}
2078
				} else {
2079
					portal_reply_page($redirurl, "error", "Username: {$username} is already authenticated using another MAC address.",
2080
						$clientmac, $clientip, $username, $password);
2081
					unlock($cpdblck);
2082
					return;
2083
				}
2084
			}
2085
		}
2086
	}
2087

    
2088
	/* read in client database */
2089
	$query = "WHERE ip = '{$clientip}'";
2090
	$tmpusername = SQLite3::escapeString(strtolower($username));
2091
	if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
2092
		$query .= " OR (username != 'unauthenticated' AND lower(username) = '{$tmpusername}')";
2093
	}
2094
	$cpdb = captiveportal_read_db($query);
2095

    
2096
	/* Snapshot the timestamp */
2097
	$allow_time = time();
2098
	$radiusservers = captiveportal_get_radius_servers();
2099
	$unsetindexes = array();
2100
	if (is_null($radiusctx)) {
2101
		$radiusctx = 'first';
2102
	}
2103

    
2104
	foreach ($cpdb as $cpentry) {
2105
		if (empty($cpentry[11])) {
2106
			$cpentry[11] = 'first';
2107
		}
2108
		/* on the same ip */
2109
		if ($cpentry[2] == $clientip) {
2110
			if (isset($config['captiveportal'][$cpzone]['nomacfilter']) || $cpentry[3] == $clientmac) {
2111
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING OLD SESSION");
2112
			} else {
2113
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING IP {$cpentry[2]} WITH DIFFERENT MAC ADDRESS {$cpentry[3]}");
2114
			}
2115
			$sessionid = $cpentry[5];
2116
			break;
2117
		} elseif (($attributes['voucher']) && ($username != 'unauthenticated') && ($cpentry[4] == $username)) {
2118
			// user logged in with an active voucher. Check for how long and calculate
2119
			// how much time we can give him (voucher credit - used time)
2120
			$remaining_time = $cpentry[0] + $cpentry[7] - $allow_time;
2121
			if ($remaining_time < 0) { // just in case.
2122
				$remaining_time = 0;
2123
			}
2124

    
2125
			/* This user was already logged in so we disconnect the old one */
2126
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2127
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2128
			$unsetindexes[] = $cpentry[5];
2129
			break;
2130
		} elseif ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && ($username != 'unauthenticated')) {
2131
			/* on the same username */
2132
			if (strcasecmp($cpentry[4], $username) == 0) {
2133
				/* This user was already logged in so we disconnect the old one */
2134
				captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2135
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2136
				$unsetindexes[] = $cpentry[5];
2137
				break;
2138
			}
2139
		}
2140
	}
2141
	unset($cpdb);
2142

    
2143
	if (!empty($unsetindexes)) {
2144
		captiveportal_remove_entries($unsetindexes);
2145
	}
2146

    
2147
	if ($attributes['voucher'] && $remaining_time <= 0) {
2148
		return 0;       // voucher already used and no time left
2149
	}
2150

    
2151
	if (!isset($sessionid)) {
2152
		/* generate unique session ID */
2153
		$tod = gettimeofday();
2154
		$sessionid = substr(md5(mt_rand() . $tod['sec'] . $tod['usec'] . $clientip . $clientmac), 0, 16);
2155

    
2156
		if ($passthrumac) {
2157
			$mac = array();
2158
			$mac['action'] = 'pass';
2159
			$mac['mac'] = $clientmac;
2160
			$mac['ip'] = $clientip; /* Used only for logging */
2161
			if (isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
2162
				$mac['username'] = $username;
2163
				if ($attributes['voucher']) {
2164
					$mac['logintype'] = "voucher";
2165
				}
2166
			}
2167
			if ($username == "unauthenticated") {
2168
				$mac['descr'] = "Auto-added";
2169
			} else {
2170
				$mac['descr'] = "Auto-added for user {$username}";
2171
			}
2172
			if (!empty($bw_up)) {
2173
				$mac['bw_up'] = $bw_up;
2174
			}
2175
			if (!empty($bw_down)) {
2176
				$mac['bw_down'] = $bw_down;
2177
			}
2178
			if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2179
				$config['captiveportal'][$cpzone]['passthrumac'] = array();
2180
			}
2181
			$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2182
			unlock($cpdblck);
2183
			$macrules = captiveportal_passthrumac_configure_entry($mac);
2184
			file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2185
			mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2186
			$writecfg = true;
2187
		} else {
2188
			/* See if a pipeno is passed, if not start sessions because this means there isn't one atm */
2189
			if (is_null($pipeno)) {
2190
				$pipeno = captiveportal_get_next_dn_ruleno();
2191
			}
2192

    
2193
			/* if the pool is empty, return appropriate message and exit */
2194
			if (is_null($pipeno)) {
2195
				portal_reply_page($redirurl, "error", "System reached maximum login capacity");
2196
				log_error("Zone: {$cpzone} - WARNING!  Captive portal has reached maximum login capacity");
2197
				unlock($cpdblck);
2198
				return;
2199
			}
2200

    
2201
			if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2202
				$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2203
				$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2204
			} else {
2205
				$dwfaultbw_up = $dwfaultbw_down = 0;
2206
			}
2207
			$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2208
			$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2209

    
2210
			$bw_up_pipeno = $pipeno;
2211
			$bw_down_pipeno = $pipeno + 1;
2212
			//$bw_up /= 1000; // Scale to Kbit/s
2213
			$_gb = @pfSense_pipe_action("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2214
			$_gb = @pfSense_pipe_action("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2215

    
2216
			$clientsn = (is_ipaddrv6($clientip)) ? 128 : 32;
2217
			if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) {
2218
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 1, $clientip, $clientsn, $clientmac, $bw_up_pipeno);
2219
			} else {
2220
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 1, $clientip, $clientsn, NULL, $bw_up_pipeno);
2221
			}
2222

    
2223
			if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) {
2224
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 2, $clientip, $clientsn, $clientmac, $bw_down_pipeno);
2225
			} else {
2226
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 2, $clientip, $clientsn, NULL, $bw_down_pipeno);
2227
			}
2228

    
2229
			if ($attributes['voucher']) {
2230
				$attributes['session_timeout'] = $remaining_time;
2231
			}
2232

    
2233
			/* handle empty attributes */
2234
			$session_timeout = (!empty($attributes['session_timeout'])) ? $attributes['session_timeout'] : 'NULL';
2235
			$idle_timeout = (!empty($attributes['idle_timeout'])) ? $attributes['idle_timeout'] : 'NULL';
2236
			$session_terminate_time = (!empty($attributes['session_terminate_time'])) ? $attributes['session_terminate_time'] : 'NULL';
2237
			$interim_interval = (!empty($attributes['interim_interval'])) ? $attributes['interim_interval'] : 'NULL';
2238

    
2239
			/* escape username */
2240
			$safe_username = SQLite3::escapeString($username);
2241

    
2242
			/* encode password in Base64 just in case it contains commas */
2243
			$bpassword = base64_encode($password);
2244
			$insertquery = "INSERT INTO captiveportal (allow_time, pipeno, ip, mac, username, sessionid, bpassword, session_timeout, idle_timeout, session_terminate_time, interim_interval, radiusctx) ";
2245
			$insertquery .= "VALUES ({$allow_time}, {$pipeno}, '{$clientip}', '{$clientmac}', '{$safe_username}', '{$sessionid}', '{$bpassword}', ";
2246
			$insertquery .= "{$session_timeout}, {$idle_timeout}, {$session_terminate_time}, {$interim_interval}, '{$radiusctx}')";
2247

    
2248
			/* store information to database */
2249
			captiveportal_write_db($insertquery);
2250
			unlock($cpdblck);
2251
			unset($insertquery, $bpassword);
2252

    
2253
			if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers[$radiusctx])) {
2254
				$acct_val = RADIUS_ACCOUNTING_START($pipeno, $username, $sessionid, $radiusservers[$radiusctx], $clientip, $clientmac);
2255
				if ($acct_val == 1) {
2256
					captiveportal_logportalauth($username, $clientmac, $clientip, $type, "RADIUS ACCOUNTING FAILED");
2257
				}
2258
			}
2259
		}
2260
	} else {
2261
		/* NOTE: #3062-11 If the pipeno has been allocated free it to not DoS the CP and maintain proper operation as in radius() case */
2262
		if (!is_null($pipeno)) {
2263
			captiveportal_free_dn_ruleno($pipeno);
2264
		}
2265

    
2266
		unlock($cpdblck);
2267
	}
2268

    
2269
	if ($writecfg == true) {
2270
		write_config();
2271
	}
2272

    
2273
	/* redirect user to desired destination */
2274
	if (!empty($attributes['url_redirection'])) {
2275
		$my_redirurl = $attributes['url_redirection'];
2276
	} else if (!empty($redirurl)) {
2277
		$my_redirurl = $redirurl;
2278
	} else if (!empty($config['captiveportal'][$cpzone]['redirurl'])) {
2279
		$my_redirurl = $config['captiveportal'][$cpzone]['redirurl'];
2280
	}
2281

    
2282
	if (isset($config['captiveportal'][$cpzone]['logoutwin_enable']) && !$passthrumac) {
2283
		$ourhostname = portal_hostname_from_client_ip($clientip);
2284
		$protocol = (isset($config['captiveportal'][$cpzone]['httpslogin'])) ? 'https://' : 'http://';
2285
		$logouturl = "{$protocol}{$ourhostname}/";
2286

    
2287
		if (isset($attributes['reply_message'])) {
2288
			$message = $attributes['reply_message'];
2289
		} else {
2290
			$message = 0;
2291
		}
2292

    
2293
		include_once("{$g['varetc_path']}/captiveportal-{$cpzone}-logout.html");
2294

    
2295
	} else {
2296
		portal_reply_page($my_redirurl, "redir", "Just redirect the user.");
2297
	}
2298

    
2299
	return $sessionid;
2300
}
2301

    
2302

    
2303
/*
2304
 * Used for when pass-through credits are enabled.
2305
 * Returns true when there was at least one free login to deduct for the MAC.
2306
 * Expired entries are removed as they are seen.
2307
 * Active entries are updated according to the configuration.
2308
 */
2309
function portal_consume_passthrough_credit($clientmac) {
2310
	global $config, $cpzone;
2311

    
2312
	if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count'])) {
2313
		$freeloginscount = $config['captiveportal'][$cpzone]['freelogins_count'];
2314
	} else {
2315
		return false;
2316
	}
2317

    
2318
	if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout'])) {
2319
		$resettimeout = $config['captiveportal'][$cpzone]['freelogins_resettimeout'];
2320
	} else {
2321
		return false;
2322
	}
2323

    
2324
	if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac) {
2325
		return false;
2326
	}
2327

    
2328
	$updatetimeouts = isset($config['captiveportal'][$cpzone]['freelogins_updatetimeouts']);
2329

    
2330
	/*
2331
	 * Read database of used MACs.  Lines are a comma-separated list
2332
	 * of the time, MAC, then the count of pass-through credits remaining.
2333
	 */
2334
	$usedmacs = captiveportal_read_usedmacs_db();
2335

    
2336
	$currenttime = time();
2337
	$found = false;
2338
	foreach ($usedmacs as $key => $usedmac) {
2339
		$usedmac = explode(",", $usedmac);
2340

    
2341
		if ($usedmac[1] == $clientmac) {
2342
			if ($usedmac[0] + ($resettimeout * 3600) > $currenttime) {
2343
				if ($usedmac[2] < 1) {
2344
					if ($updatetimeouts) {
2345
						$usedmac[0] = $currenttime;
2346
						unset($usedmacs[$key]);
2347
						$usedmacs[] = implode(",", $usedmac);
2348
						captiveportal_write_usedmacs_db($usedmacs);
2349
					}
2350

    
2351
					return false;
2352
				} else {
2353
					$usedmac[2] -= 1;
2354
					$usedmacs[$key] = implode(",", $usedmac);
2355
				}
2356

    
2357
				$found = true;
2358
			} else {
2359
				unset($usedmacs[$key]);
2360
			}
2361

    
2362
			break;
2363
		} else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime) {
2364
			unset($usedmacs[$key]);
2365
		}
2366
	}
2367

    
2368
	if (!$found) {
2369
		$usedmac = array($currenttime, $clientmac, $freeloginscount - 1);
2370
		$usedmacs[] = implode(",", $usedmac);
2371
	}
2372

    
2373
	captiveportal_write_usedmacs_db($usedmacs);
2374
	return true;
2375
}
2376

    
2377
function captiveportal_read_usedmacs_db() {
2378
	global $g, $cpzone;
2379

    
2380
	$cpumaclck = lock("captiveusedmacs{$cpzone}");
2381
	if (file_exists("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db")) {
2382
		$usedmacs = file("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2383
		if (!$usedmacs) {
2384
			$usedmacs = array();
2385
		}
2386
	} else {
2387
		$usedmacs = array();
2388
	}
2389

    
2390
	unlock($cpumaclck);
2391
	return $usedmacs;
2392
}
2393

    
2394
function captiveportal_write_usedmacs_db($usedmacs) {
2395
	global $g, $cpzone;
2396

    
2397
	$cpumaclck = lock("captiveusedmacs{$cpzone}", LOCK_EX);
2398
	@file_put_contents("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", implode("\n", $usedmacs));
2399
	unlock($cpumaclck);
2400
}
2401

    
2402
function captiveportal_blocked_mac($mac) {
2403
	global $config, $g, $cpzone;
2404

    
2405
	if (empty($mac) || !is_macaddr($mac)) {
2406
		return false;
2407
	}
2408

    
2409
	if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2410
		return false;
2411
	}
2412

    
2413
	foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) {
2414
		if (($passthrumac['action'] == 'block') &&
2415
		    ($passthrumac['mac'] == strtolower($mac))) {
2416
			return true;
2417
		}
2418
	}
2419

    
2420
	return false;
2421

    
2422
}
2423

    
2424
function captiveportal_send_server_accounting($off = false) {
2425
	global $cpzone, $config;
2426

    
2427
	if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
2428
		return;
2429
	}
2430
	if ($off) {
2431
		$racct = new Auth_RADIUS_Acct_Off;
2432
	} else {
2433
		$racct = new Auth_RADIUS_Acct_On;
2434
	}
2435
	$radiusservers = captiveportal_get_radius_servers();
2436
	if (empty($radiusservers)) {
2437
		return;
2438
	}
2439
	foreach ($radiusservers['first'] as $radsrv) {
2440
		// Add a new server to our instance
2441
		$racct->addServer($radsrv['ipaddr'], $radsrv['acctport'], $radsrv['key']);
2442
	}
2443
	if (PEAR::isError($racct->start())) {
2444
		$retvalue['acct_val'] = 1;
2445
		$retvalue['error'] = $racct->getMessage();
2446

    
2447
		// If we encounter an error immediately stop this function and go back
2448
		$racct->close();
2449
		return $retvalue;
2450
	}
2451
	// Send request
2452
	$result = $racct->send();
2453
	// Evaluation of the response
2454
	// 5 -> Accounting-Response
2455
	// See RFC2866 for this.
2456
	if (PEAR::isError($result)) {
2457
		$retvalue['acct_val'] = 1;
2458
		$retvalue['error'] = $result->getMessage();
2459
	} else if ($result === true) {
2460
		$retvalue['acct_val'] = 5 ;
2461
	} else {
2462
		$retvalue['acct_val'] = 1 ;
2463
	}
2464

    
2465
	$racct->close();
2466
	return $retvalue;
2467
}
2468

    
2469
function captiveportal_isip_logged($clientip) {
2470
	global $g, $cpzone;
2471

    
2472
	/* read in client database */
2473
	$query = "WHERE ip = '{$clientip}'";
2474
	$cpdb = captiveportal_read_db($query);
2475
	foreach ($cpdb as $cpentry) {
2476
		return $cpentry;
2477
	}
2478
}
2479
?>
(7-7/65)