Project

General

Profile

Download (81.6 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 Rubicon Communications, LLC (Netgate)
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(10); // NAS-Request
374

    
375
		/* remove old information */
376
		unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
377
		unlink_if_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db");
378
		unlink_if_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules");
379
		/* Release allocated pipes for this zone */
380
		captiveportal_free_dnrules();
381

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

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

    
403
	unlock($captiveportallck);
404

    
405
	return 0;
406
}
407

    
408
function captiveportal_init_webgui() {
409
	global $config, $cpzone;
410

    
411
	if (is_array($config['captiveportal'])) {
412
		foreach ($config['captiveportal'] as $cpkey => $cp) {
413
			$cpzone = $cpkey;
414
			captiveportal_init_webgui_zone($cp);
415
		}
416
	}
417
}
418

    
419
function captiveportal_init_webgui_zonename($zone) {
420
	global $config, $cpzone;
421

    
422
	if (isset($config['captiveportal'][$zone])) {
423
		$cpzone = $zone;
424
		captiveportal_init_webgui_zone($config['captiveportal'][$zone]);
425
	}
426
}
427

    
428
function captiveportal_init_webgui_zone($cpcfg) {
429
	global $g, $config, $cpzone;
430

    
431
	if (!isset($cpcfg['enable'])) {
432
		return;
433
	}
434

    
435
	if (isset($cpcfg['httpslogin'])) {
436
		$cert = lookup_cert($cpcfg['certref']);
437
		$crt = base64_decode($cert['crt']);
438
		$key = base64_decode($cert['prv']);
439
		$ca = ca_chain($cert);
440

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

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

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

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

    
473
function captiveportal_init_rules_byinterface($interface) {
474
	global $cpzone, $cpzoneid, $config;
475

    
476
	if (!is_array($config['captiveportal'])) {
477
		return;
478
	}
479

    
480
	foreach ($config['captiveportal'] as $cpkey => $cp) {
481
		$cpzone = $cpkey;
482
		$cpzoneid = $cp['zoneid'];
483
		$cpinterfaces = explode(",", $cp['interface']);
484
		if (in_array($interface, $cpinterfaces)) {
485
			captiveportal_init_rules();
486
			break;
487
		}
488
	}
489
}
490

    
491
/* reinit will disconnect all users, be careful! */
492
function captiveportal_init_rules($reinit = false) {
493
	global $config, $g, $cpzone, $cpzoneid;
494

    
495
	if (!isset($config['captiveportal'][$cpzone]['enable'])) {
496
		return;
497
	}
498

    
499
	captiveportal_load_modules();
500
	mwexec("/sbin/ipfw zone {$cpzoneid} create", true);
501

    
502
	/* Cleanup so nothing is leaked */
503
	captiveportal_free_dnrules();
504
	unlink_if_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules");
505

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

    
536
	if ($reinit == false) {
537
		$captiveportallck = lock("captiveportal{$cpzone}");
538
	}
539

    
540
	$cprules = <<<EOD
541

    
542
flush
543
add 65291 allow pfsync from any to any
544
add 65292 allow carp from any to any
545

    
546
# layer 2: pass ARP
547
add 65301 pass layer2 mac-type arp,rarp
548
# pfsense requires for WPA
549
add 65302 pass layer2 mac-type 0x888e,0x88c7
550
# PPP Over Ethernet Session Stage/Discovery Stage
551
add 65303 pass layer2 mac-type 0x8863,0x8864
552

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

    
556
EOD;
557

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

    
572
	/* Allowed ips */
573
	$cprules .= "add {$rulenum} pipe tablearg ip from table(3) to any in\n";
574
	$rulenum++;
575
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(4) in\n";
576
	$rulenum++;
577
	$cprules .= "add {$rulenum} pipe tablearg ip from table(3) to any out\n";
578
	$rulenum++;
579
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(4) out\n";
580
	$rulenum++;
581

    
582
	/* Authenticated users rules. */
583
	$cprules .= "add {$rulenum} pipe tablearg ip from table(1) to any in\n";
584
	$rulenum++;
585
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(2) out\n";
586
	$rulenum++;
587

    
588
	if (!empty($config['captiveportal'][$cpzone]['listenporthttp'])) {
589
		$listenporthttp = $config['captiveportal'][$cpzone]['listenporthttp'];
590
	} else {
591
		$listenporthttp = 8000 + $cpzoneid;
592
	}
593

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

    
605
	$cprules .= <<<EOD
606

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

    
614
EOD;
615

    
616
	/* generate passthru mac database */
617
	$cprules .= captiveportal_passthrumac_configure(true);
618
	$cprules .= "\n";
619

    
620
	/* allowed ipfw rules to make allowed ip work */
621
	$cprules .= captiveportal_allowedip_configure();
622

    
623
	/* allowed ipfw rules to make allowed hostnames work */
624
	$cprules .= captiveportal_allowedhostname_configure();
625

    
626
	/* load rules */
627
	file_put_contents("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules", $cprules);
628
	mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/ipfw_{$cpzone}.cp.rules", true);
629
	//@unlink("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules");
630
	unset($cprules);
631

    
632
	if ($reinit == false) {
633
		unlock($captiveportallck);
634
	}
635
}
636

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

    
646
	if (empty($cpzone)) {
647
		return;
648
	}
649

    
650
	$cpcfg = $config['captiveportal'][$cpzone];
651
	$vcpcfg = $config['voucher'][$cpzone];
652

    
653
	/* check for expired entries */
654
	$idletimeout = 0;
655
	$timeout = 0;
656
	if (!empty($cpcfg['timeout']) && is_numeric($cpcfg['timeout'])) {
657
		$timeout = $cpcfg['timeout'] * 60;
658
	}
659

    
660
	if (!empty($cpcfg['idletimeout']) && is_numeric($cpcfg['idletimeout'])) {
661
		$idletimeout = $cpcfg['idletimeout'] * 60;
662
	}
663

    
664
	/* Is there any job to do? */
665
	if (!$timeout && !$idletimeout && !isset($cpcfg['reauthenticate']) &&
666
	    !isset($cpcfg['radiussession_timeout']) && !isset($vcpcfg['enable'])) {
667
		return;
668
	}
669

    
670
	$radiussrvs = captiveportal_get_radius_servers();
671

    
672
	/* Read database */
673
	/* NOTE: while this can be simplified in non radius case keep as is for now */
674
	$cpdb = captiveportal_read_db();
675

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

    
686
		$timedout = false;
687
		$term_cause = 1;
688
		if (empty($cpentry[11])) {
689
			$cpentry[11] = 'first';
690
		}
691
		$radiusservers = $radiussrvs[$cpentry[11]];
692

    
693
		/* hard timeout? */
694
		if ($timeout) {
695
			if (($pruning_time - $cpentry[0]) >= $timeout) {
696
				$timedout = true;
697
				$term_cause = 5; // Session-Timeout
698
			}
699
		}
700

    
701
		/* Session-Terminate-Time */
702
		if (!$timedout && !empty($cpentry[9])) {
703
			if ($pruning_time >= $cpentry[9]) {
704
				$timedout = true;
705
				$term_cause = 5; // Session-Timeout
706
			}
707
		}
708

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

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

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

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

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

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

    
830
	captiveportal_prune_old_automac();
831

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

    
837
	/* write database */
838
	if (!empty($unsetindexes)) {
839
		captiveportal_remove_entries($unsetindexes);
840
	}
841
}
842

    
843
function captiveportal_prune_old_automac() {
844
	global $g, $config, $cpzone, $cpzoneid;
845

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

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

    
912
	$stop_time = (empty($stop_time)) ? time() : $stop_time;
913

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

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

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

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

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

    
966
}
967

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

    
972
	$sessionid = SQLite3::escapeString($sessionid);
973
	$radiusservers = captiveportal_get_radius_servers();
974

    
975
	/* read database */
976
	$result = captiveportal_read_db("WHERE sessionid = '{$sessionid}'");
977

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

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

    
993
/* remove all clients */
994
function captiveportal_disconnect_all($term_cause = 6, $logoutReason = "DISCONNECT") {
995
	global $g, $config, $cpzone, $cpzoneid;
996

    
997
	/* check if we're pruning old entries and eventually wait */
998
	$rcprunelock = try_lock("rcprunecaptiveportal{$cpzone}", 15);
999

    
1000
	/* if we still don't have the lock, unlock forcefully and take it */
1001
	if (!$rcprunelock) {
1002
		log_error("CP zone ${cpzone}: could not obtain the lock for more than 15 seconds, lock taken forcefully to disconnect all users");
1003
		unlock_force("rcprunecaptiveportal{$cpzone}");
1004
		$rcprunelock = lock("rcprunecaptiveportal{$cpzone}", LOCK_EX);
1005
	}
1006

    
1007
	/* take a lock so new users won't be able to log in */
1008
	$cpdblck = lock("captiveportaldb{$cpzone}", LOCK_EX);
1009

    
1010
	captiveportal_radius_stop_all($term_cause, $logoutReason);
1011

    
1012
	/* remove users from the database */
1013
	$cpdb = captiveportal_read_db();
1014
	$unsetindexes = array_column($cpdb,5);
1015
	if (!empty($unsetindexes)) {
1016
		captiveportal_remove_entries($unsetindexes);
1017
	}
1018

    
1019
	/* reinit ipfw rules */
1020
	mwexec("/sbin/ipfw zone {$cpzoneid} destroy", true);
1021
	captiveportal_init_rules(true);
1022

    
1023
	unlock($cpdblck);
1024
	unlock($rcprunelock);
1025
}
1026

    
1027
/* send RADIUS acct stop for all current clients */
1028
function captiveportal_radius_stop_all($term_cause = 6, $logoutReason = "DISCONNECT") {
1029
	global $g, $config, $cpzone, $cpzoneid;
1030

    
1031
	$cpdb = captiveportal_read_db();
1032

    
1033
	$radacct = isset($config['captiveportal'][$cpzone]['radacct_enable']) ? true : false;
1034
	if ($radacct) {
1035
		$radiusservers = captiveportal_get_radius_servers();
1036
	}
1037

    
1038
	foreach ($cpdb as $cpentry) {
1039
		if ($radacct) {
1040
			if (!empty($radiusservers)) {
1041
				if (empty($cpentry[11])) {
1042
					$cpentry[11] = 'first';
1043
				}
1044
				if (!empty($radiusservers[$cpentry[11]])) {
1045
					RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
1046
						$cpentry[4], // username
1047
						$cpentry[5], // sessionid
1048
						$cpentry[0], // start time
1049
						$radiusservers[$cpentry[11]],
1050
						$cpentry[2], // clientip
1051
						$cpentry[3], // clientmac
1052
						$term_cause);
1053
				}
1054
			}
1055
		}
1056
		captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], $logoutReason);
1057
	}
1058
	unset($cpdb);
1059
}
1060

    
1061
function captiveportal_passthrumac_configure_entry($macent, $pipeinrule = false) {
1062
	global $config, $g, $cpzone;
1063

    
1064
	$bwUp = 0;
1065
	if (!empty($macent['bw_up'])) {
1066
		$bwUp = $macent['bw_up'];
1067
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1068
		$bwUp = $config['captiveportal'][$cpzone]['bwdefaultup'];
1069
	}
1070
	$bwDown = 0;
1071
	if (!empty($macent['bw_down'])) {
1072
		$bwDown = $macent['bw_down'];
1073
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1074
		$bwDown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1075
	}
1076

    
1077
	$ruleno = captiveportal_get_next_ipfw_ruleno();
1078

    
1079
	if ($macent['action'] == 'pass') {
1080
		$rules = "";
1081
		$pipeno = captiveportal_get_next_dn_ruleno();
1082

    
1083
		$pipeup = $pipeno;
1084
		if ($pipeinrule == true) {
1085
			$_gb = @pfSense_pipe_action("pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16");
1086
		} else {
1087
			$rules .= "pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16\n";
1088
		}
1089

    
1090
		$pipedown = $pipeno + 1;
1091
		if ($pipeinrule == true) {
1092
			$_gb = @pfSense_pipe_action("pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16");
1093
		} else {
1094
			$rules .= "pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16\n";
1095
		}
1096

    
1097
		$rules .= "add {$ruleno} pipe {$pipeup} ip from any to any MAC any {$macent['mac']}\n";
1098
		$ruleno++;
1099
		$rules .= "add {$ruleno} pipe {$pipedown} ip from any to any MAC {$macent['mac']} any\n";
1100
	}
1101

    
1102
	return $rules;
1103
}
1104

    
1105
function captiveportal_passthrumac_delete_entry($macent) {
1106
	$rules = "";
1107

    
1108
	if ($macent['action'] == 'pass') {
1109
		$ruleno = captiveportal_get_ipfw_passthru_ruleno($macent['mac']);
1110

    
1111
		if (!$ruleno) {
1112
			return $rules;
1113
		}
1114

    
1115
		captiveportal_free_ipfw_ruleno($ruleno);
1116

    
1117
		$rules .= "delete {$ruleno}\n";
1118
		$rules .= "delete " . ++$ruleno . "\n";
1119

    
1120
		$pipeno = captiveportal_get_dn_passthru_ruleno($macent['mac']);
1121

    
1122
		if (!empty($pipeno)) {
1123
			captiveportal_free_dn_ruleno($pipeno);
1124
			$rules .= "pipe delete " . $pipeno . "\n";
1125
			$rules .= "pipe delete " . ++$pipeno . "\n";
1126
		}
1127
	}
1128

    
1129
	return $rules;
1130
}
1131

    
1132
function captiveportal_passthrumac_configure($filename = false, $startindex = 0, $stopindex = 0) {
1133
	global $config, $g, $cpzone;
1134

    
1135
	$rules = "";
1136

    
1137
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1138
		if ($stopindex > 0) {
1139
			$fd = fopen($filename, "w");
1140
			for ($idx = $startindex; $idx <= $stopindex; $idx++) {
1141
				if (isset($config['captiveportal'][$cpzone]['passthrumac'][$idx])) {
1142
					$rules = captiveportal_passthrumac_configure_entry($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
1143
					fwrite($fd, $rules);
1144
				}
1145
			}
1146
			fclose($fd);
1147

    
1148
			return;
1149
		} else {
1150
			$nentries = count($config['captiveportal'][$cpzone]['passthrumac']);
1151
			if ($nentries > 2000) {
1152
				$nloops = $nentries / 1000;
1153
				$remainder= $nentries % 1000;
1154
				for ($i = 0; $i < $nloops; $i++) {
1155
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . ((($i+1) * 1000) - 1) . "\"");
1156
				}
1157
				if ($remainder > 0) {
1158
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . (($i* 1000) + $remainder) ."\"");
1159
				}
1160
			} else {
1161
				foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1162
					$rules .= captiveportal_passthrumac_configure_entry($macent, true);
1163
				}
1164
			}
1165
		}
1166
	}
1167

    
1168
	return $rules;
1169
}
1170

    
1171
function captiveportal_passthrumac_findbyname($username) {
1172
	global $config, $cpzone;
1173

    
1174
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1175
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1176
			if ($macent['username'] == $username) {
1177
				return $macent;
1178
			}
1179
		}
1180
	}
1181
	return NULL;
1182
}
1183

    
1184
/*
1185
 * table (3=IN)/(4=OUT) hold allowed ip's without bw limits
1186
 */
1187
function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) {
1188
	global $g;
1189

    
1190
	/*  Instead of copying this entire function for something
1191
	 *  easy such as hostname vs ip address add this check
1192
	 */
1193
	if ($ishostname === true) {
1194
		if (!platform_booting()) {
1195
			$ipaddress = gethostbyname($ipent['hostname']);
1196
			if (!is_ipaddr($ipaddress)) {
1197
				return;
1198
			}
1199
		} else {
1200
			$ipaddress = "";
1201
		}
1202
	} else {
1203
		$ipaddress = $ipent['ip'];
1204
	}
1205

    
1206
	$rules = "";
1207
	$cp_filterdns_conf = "";
1208
	$enBwup = 0;
1209
	if (!empty($ipent['bw_up'])) {
1210
		$enBwup = intval($ipent['bw_up']);
1211
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1212
		$enBwup = $config['captiveportal'][$cpzone]['bwdefaultup'];
1213
	}
1214
	$enBwdown = 0;
1215
	if (!empty($ipent['bw_down'])) {
1216
		$enBwdown = intval($ipent['bw_down']);
1217
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1218
		$enBwdown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1219
	}
1220

    
1221
	$pipeno = captiveportal_get_next_dn_ruleno();
1222
	$_gb = @pfSense_pipe_action("pipe {$pipeno} config bw {$enBwup}Kbit/s queue 100 buckets 16");
1223
	$pipedown = $pipeno + 1;
1224
	$_gb = @pfSense_pipe_action("pipe {$pipedown} config bw {$enBwdown}Kbit/s queue 100 buckets 16");
1225
	if ($ishostname === true) {
1226
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} 3 pipe {$pipeno}\n";
1227
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} 4 pipe {$pipedown}\n";
1228
		if (!is_ipaddr($ipaddress)) {
1229
			return array("", $cp_filterdns_conf);
1230
		}
1231
	}
1232
	$subnet = "";
1233
	if (!empty($ipent['sn'])) {
1234
		$subnet = "/{$ipent['sn']}";
1235
	}
1236
	$rules .= "table 3 add {$ipaddress}{$subnet} {$pipeno}\n";
1237
	$rules .= "table 4 add {$ipaddress}{$subnet} {$pipedown}\n";
1238

    
1239
	if ($ishostname === true) {
1240
		return array($rules, $cp_filterdns_conf);
1241
	} else {
1242
		return $rules;
1243
	}
1244
}
1245

    
1246
function captiveportal_allowedhostname_configure() {
1247
	global $config, $g, $cpzone, $cpzoneid;
1248

    
1249
	$rules = "";
1250
	if (is_array($config['captiveportal'][$cpzone]['allowedhostname'])) {
1251
		$rules = "\n# captiveportal_allowedhostname_configure()\n";
1252
		$cp_filterdns_conf = "";
1253
		foreach ($config['captiveportal'][$cpzone]['allowedhostname'] as $hostnameent) {
1254
			$tmprules = captiveportal_allowedip_configure_entry($hostnameent, true);
1255
			$rules .= $tmprules[0];
1256
			$cp_filterdns_conf .= $tmprules[1];
1257
		}
1258
		$cp_filterdns_filename = "{$g['varetc_path']}/filterdns-{$cpzone}-captiveportal.conf";
1259
		@file_put_contents($cp_filterdns_filename, $cp_filterdns_conf);
1260
		unset($cp_filterdns_conf);
1261
		if (isvalidpid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid")) {
1262
			sigkillbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid", "HUP");
1263
		} else {
1264
			mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid -i 300 -c {$cp_filterdns_filename} -y {$cpzoneid} -d 1");
1265
		}
1266
	} else {
1267
		killbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1268
		@unlink("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1269
	}
1270

    
1271
	return $rules;
1272
}
1273

    
1274
function captiveportal_allowedip_configure() {
1275
	global $config, $g, $cpzone;
1276

    
1277
	$rules = "";
1278
	if (is_array($config['captiveportal'][$cpzone]['allowedip'])) {
1279
		foreach ($config['captiveportal'][$cpzone]['allowedip'] as $ipent) {
1280
			$rules .= captiveportal_allowedip_configure_entry($ipent);
1281
		}
1282
	}
1283

    
1284
	return $rules;
1285
}
1286

    
1287
/* get last activity timestamp given client IP address */
1288
function captiveportal_get_last_activity($ip, $mac = NULL, $table = 1) {
1289
	global $cpzoneid;
1290

    
1291
	$ipfwoutput = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, $table, $ip, $mac);
1292
	/* Reading only from one of the tables is enough of approximation. */
1293
	if (is_array($ipfwoutput)) {
1294
		/* Workaround for #46652 */
1295
		if ($ipfwoutput['packets'] > 0) {
1296
			return $ipfwoutput['timestamp'];
1297
		} else {
1298
			return 0;
1299
		}
1300
	}
1301

    
1302
	return 0;
1303
}
1304

    
1305
function captiveportal_init_radius_servers() {
1306
	global $config, $g, $cpzone;
1307

    
1308
	/* generate radius server database */
1309
	if ($config['captiveportal'][$cpzone]['radiusip'] &&
1310
	    (!isset($config['captiveportal'][$cpzone]['auth_method']) || $config['captiveportal'][$cpzone]['auth_method'] == "radius")) {
1311
		$radiusip = $config['captiveportal'][$cpzone]['radiusip'];
1312
		$radiusip2 = ($config['captiveportal'][$cpzone]['radiusip2']) ? $config['captiveportal'][$cpzone]['radiusip2'] : null;
1313
		$radiusip3 = ($config['captiveportal'][$cpzone]['radiusip3']) ? $config['captiveportal'][$cpzone]['radiusip3'] : null;
1314
		$radiusip4 = ($config['captiveportal'][$cpzone]['radiusip4']) ? $config['captiveportal'][$cpzone]['radiusip4'] : null;
1315

    
1316
		if ($config['captiveportal'][$cpzone]['radiusport']) {
1317
			$radiusport = $config['captiveportal'][$cpzone]['radiusport'];
1318
		} else {
1319
			$radiusport = 1812;
1320
		}
1321
		if ($config['captiveportal'][$cpzone]['radiusacctport']) {
1322
			$radiusacctport = $config['captiveportal'][$cpzone]['radiusacctport'];
1323
		} else {
1324
			$radiusacctport = 1813;
1325
		}
1326
		if ($config['captiveportal'][$cpzone]['radiusport2']) {
1327
			$radiusport2 = $config['captiveportal'][$cpzone]['radiusport2'];
1328
		} else {
1329
			$radiusport2 = 1812;
1330
		}
1331
		if ($config['captiveportal'][$cpzone]['radiusport3']) {
1332
			$radiusport3 = $config['captiveportal'][$cpzone]['radiusport3'];
1333
		} else {
1334
			$radiusport3 = 1812;
1335
		}
1336
		if ($config['captiveportal'][$cpzone]['radiusport4']) {
1337
			$radiusport4 = $config['captiveportal'][$cpzone]['radiusport4'];
1338
		} else {
1339
			$radiusport4 = 1812;
1340
		}
1341

    
1342
		$radiuskey = $config['captiveportal'][$cpzone]['radiuskey'];
1343
		$radiuskey2 = $config['captiveportal'][$cpzone]['radiuskey2'];
1344
		$radiuskey3 = $config['captiveportal'][$cpzone]['radiuskey3'];
1345
		$radiuskey4 = $config['captiveportal'][$cpzone]['radiuskey4'];
1346

    
1347
		$cprdsrvlck = lock("captiveportalradius{$cpzone}", LOCK_EX);
1348
		$fd = @fopen("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db", "w");
1349
		if (!$fd) {
1350
			captiveportal_syslog("Error: cannot open RADIUS DB file in captiveportal_configure().\n");
1351
			unlock($cprdsrvlck);
1352
			return 1;
1353
		}
1354
		if (isset($radiusip)) {
1355
			fwrite($fd, $radiusip . "," . $radiusport . "," . $radiusacctport . "," . $radiuskey . ",first");
1356
		}
1357
		if (isset($radiusip2)) {
1358
			fwrite($fd, "\n" . $radiusip2 . "," . $radiusport2 . "," . $radiusacctport . "," . $radiuskey2 . ",first");
1359
		}
1360
		if (isset($radiusip3)) {
1361
			fwrite($fd, "\n" . $radiusip3 . "," . $radiusport3 . "," . $radiusacctport . "," . $radiuskey3 . ",second");
1362
		}
1363
		if (isset($radiusip4)) {
1364
			fwrite($fd, "\n" . $radiusip4 . "," . $radiusport4 . "," . $radiusacctport . "," . $radiuskey4 . ",second");
1365
		}
1366

    
1367
		fclose($fd);
1368
		unlock($cprdsrvlck);
1369
	}
1370
}
1371

    
1372
/* read RADIUS servers into array */
1373
function captiveportal_get_radius_servers() {
1374
	global $g, $cpzone;
1375

    
1376
	$cprdsrvlck = lock("captiveportalradius{$cpzone}");
1377
	if (file_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db")) {
1378
		$radiusservers = array();
1379
		$cpradiusdb = file("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db",
1380
		FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1381
		if ($cpradiusdb) {
1382
			foreach ($cpradiusdb as $cpradiusentry) {
1383
				$line = trim($cpradiusentry);
1384
				if ($line) {
1385
					$radsrv = array();
1386
					list($radsrv['ipaddr'], $radsrv['port'], $radsrv['acctport'], $radsrv['key'], $context) = explode(",", $line);
1387
				}
1388
				if (empty($context)) {
1389
					if (!is_array($radiusservers['first'])) {
1390
						$radiusservers['first'] = array();
1391
					}
1392
					$radiusservers['first'] = $radsrv;
1393
				} else {
1394
					if (!is_array($radiusservers[$context])) {
1395
						$radiusservers[$context] = array();
1396
					}
1397
					$radiusservers[$context][] = $radsrv;
1398
				}
1399
			}
1400
		}
1401
		unlock($cprdsrvlck);
1402
		return $radiusservers;
1403
	}
1404

    
1405
	unlock($cprdsrvlck);
1406
	return false;
1407
}
1408

    
1409
/* log successful captive portal authentication to syslog */
1410
/* part of this code from php.net */
1411
function captiveportal_logportalauth($user, $mac, $ip, $status, $message = null) {
1412
	// Log it
1413
	if (!$message) {
1414
		$message = "{$status}: {$user}, {$mac}, {$ip}";
1415
	} else {
1416
		$message = trim($message);
1417
		$message = "{$status}: {$user}, {$mac}, {$ip}, {$message}";
1418
	}
1419
	captiveportal_syslog($message);
1420
}
1421

    
1422
/* log simple messages to syslog */
1423
function captiveportal_syslog($message) {
1424
	global $cpzone;
1425

    
1426
	$message = trim($message);
1427
	$message = "Zone: {$cpzone} - {$message}";
1428
	openlog("logportalauth", LOG_PID, LOG_LOCAL4);
1429
	// Log it
1430
	syslog(LOG_INFO, $message);
1431
	closelog();
1432
}
1433

    
1434
function radius($username, $password, $clientip, $clientmac, $type, $radiusctx = null) {
1435
	global $g, $config, $cpzoneid;
1436

    
1437
	$pipeno = captiveportal_get_next_dn_ruleno();
1438

    
1439
	/* If the pool is empty, return appropriate message and fail authentication */
1440
	if (empty($pipeno)) {
1441
		$auth_list = array();
1442
		$auth_list['auth_val'] = 1;
1443
		$auth_list['error'] = "System reached maximum login capacity";
1444
		return $auth_list;
1445
	}
1446

    
1447
	$radiusservers = captiveportal_get_radius_servers();
1448

    
1449
	if (is_null($radiusctx)) {
1450
		$radiusctx = 'first';
1451
	}
1452

    
1453
	$auth_list = RADIUS_AUTHENTICATION($username,
1454
		$password,
1455
		$radiusservers[$radiusctx],
1456
		$clientip,
1457
		$clientmac,
1458
		$pipeno);
1459

    
1460
	if ($auth_list['auth_val'] == 2) {
1461
		captiveportal_logportalauth($username, $clientmac, $clientip, $type);
1462
		$sessionid = portal_allow($clientip,
1463
			$clientmac,
1464
			$username,
1465
			$password,
1466
			$auth_list,
1467
			$pipeno,
1468
			$radiusctx);
1469
	} else {
1470
		captiveportal_free_dn_ruleno($pipeno);
1471
	}
1472

    
1473
	return $auth_list;
1474
}
1475

    
1476
function captiveportal_opendb() {
1477
	global $g, $config, $cpzone, $cpzoneid;
1478

    
1479
	$db_path = "{$g['vardb_path']}/captiveportal{$cpzone}.db";
1480
	$createquery = "CREATE TABLE IF NOT EXISTS captiveportal (" .
1481
				"allow_time INTEGER, pipeno INTEGER, ip TEXT, mac TEXT, username TEXT, " .
1482
				"sessionid TEXT, bpassword TEXT, session_timeout INTEGER, idle_timeout INTEGER, " .
1483
				"session_terminate_time INTEGER, interim_interval INTEGER, radiusctx TEXT); " .
1484
			"CREATE UNIQUE INDEX IF NOT EXISTS idx_active ON captiveportal (sessionid, username); " .
1485
			"CREATE INDEX IF NOT EXISTS user ON captiveportal (username); " .
1486
			"CREATE INDEX IF NOT EXISTS ip ON captiveportal (ip); " .
1487
			"CREATE INDEX IF NOT EXISTS starttime ON captiveportal (allow_time)";
1488

    
1489
	try {
1490
		$DB = new SQLite3($db_path);
1491
		$DB->busyTimeout(60000);
1492
	} catch (Exception $e) {
1493
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: " . $e->getMessage() . " -- Trying again.");
1494
		unlink_if_exists($db_path);
1495
		try {
1496
			$DB = new SQLite3($db_path);
1497
			$DB->busyTimeout(60000);
1498
		} catch (Exception $e) {
1499
			captiveportal_syslog("Still could not open {$db_path} as an sqlite database for {$cpzone}. Error message: " . $e->getMessage() . " -- Remove the database file manually and ensure there is enough free space.");
1500
			return;
1501
		}
1502
	}
1503

    
1504
	if (!$DB) {
1505
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Trying again.");
1506
		unlink_if_exists($db_path);
1507
		$DB = new SQLite3($db_path);
1508
		$DB->busyTimeout(60000);
1509
		if (!$DB) {
1510
			captiveportal_syslog("Still could not open {$db_path} as an sqlite database for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Remove the database file manually and ensure there is enough free space.");
1511
			return;
1512
		}
1513
	}
1514

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

    
1518
		/* If unable to initialize the database, reset and try again. */
1519
		$DB->close();
1520
		unset($DB);
1521
		unlink_if_exists($db_path);
1522
		$DB = new SQLite3($db_path);
1523
		$DB->busyTimeout(60000);
1524
		if ($DB->exec($createquery)) {
1525
			captiveportal_syslog("Successfully reinitialized tables for {$cpzone} -- database has been reset.");
1526
			if (!is_numericint($cpzoneid)) {
1527
				if (is_array($config['captiveportal'])) {
1528
					foreach ($config['captiveportal'] as $cpkey => $cp) {
1529
						if ($cpzone == $cpkey) {
1530
							$cpzoneid = $cp['zoneid'];
1531
						}
1532
					}
1533
				}
1534
			}
1535
			if (is_numericint($cpzoneid)) {
1536
				mwexec("/sbin/ipfw -x $cpzoneid table all flush");
1537
				captiveportal_syslog("Flushed tables for {$cpzone} after database reset.");
1538
			}
1539
		} else {
1540
			captiveportal_syslog("Still unable to create tables for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Remove the database file manually and try again.");
1541
		}
1542
	}
1543

    
1544
	return $DB;
1545
}
1546

    
1547
/* read captive portal DB into array */
1548
function captiveportal_read_db($query = "") {
1549
	$cpdb = array();
1550

    
1551
	$DB = captiveportal_opendb();
1552
	if ($DB) {
1553
		$response = $DB->query("SELECT * FROM captiveportal {$query}");
1554
		if ($response != FALSE) {
1555
			while ($row = $response->fetchArray()) {
1556
				$cpdb[] = $row;
1557
			}
1558
		}
1559
		$DB->close();
1560
	}
1561

    
1562
	return $cpdb;
1563
}
1564

    
1565
function captiveportal_remove_entries($remove) {
1566

    
1567
	if (!is_array($remove) || empty($remove)) {
1568
		return;
1569
	}
1570

    
1571
	$query = "DELETE FROM captiveportal WHERE sessionid in (";
1572
	foreach ($remove as $idx => $unindex) {
1573
		$query .= "'{$unindex}'";
1574
		if ($idx < (count($remove) - 1)) {
1575
			$query .= ",";
1576
		}
1577
	}
1578
	$query .= ")";
1579
	captiveportal_write_db($query);
1580
}
1581

    
1582
/* write captive portal DB */
1583
function captiveportal_write_db($queries) {
1584
	global $g;
1585

    
1586
	if (is_array($queries)) {
1587
		$query = implode(";", $queries);
1588
	} else {
1589
		$query = $queries;
1590
	}
1591

    
1592
	$DB = captiveportal_opendb();
1593
	if ($DB) {
1594
		$DB->exec("BEGIN TRANSACTION");
1595
		$result = $DB->exec($query);
1596
		if (!$result) {
1597
			captiveportal_syslog("Trying to modify DB returned error: {$DB->lastErrorMsg()}");
1598
		} else {
1599
			$DB->exec("END TRANSACTION");
1600
		}
1601
		$DB->close();
1602
		return $result;
1603
	} else {
1604
		return true;
1605
	}
1606
}
1607

    
1608
function captiveportal_write_elements() {
1609
	global $g, $config, $cpzone;
1610

    
1611
	$cpcfg = $config['captiveportal'][$cpzone];
1612

    
1613
	if (!is_dir($g['captiveportal_element_path'])) {
1614
		@mkdir($g['captiveportal_element_path']);
1615
	}
1616

    
1617
	if (is_array($cpcfg['element'])) {
1618
		conf_mount_rw();
1619
		foreach ($cpcfg['element'] as $data) {
1620
			/* Do not attempt to decode or write out empty files. */
1621
			if (empty($data['content']) || empty(base64_decode($data['content']))) {
1622
				unlink_if_exists("{$g['captiveportal_element_path']}/{$data['name']}");
1623
				touch("{$g['captiveportal_element_path']}/{$data['name']}");
1624
			} elseif (!@file_put_contents("{$g['captiveportal_element_path']}/{$data['name']}", base64_decode($data['content']))) {
1625
				printf(gettext("Error: cannot open '%s' in captiveportal_write_elements()%s"), $data['name'], "\n");
1626
				return 1;
1627
			}
1628
			if (!file_exists("{$g['captiveportal_path']}/{$data['name']}")) {
1629
				@symlink("{$g['captiveportal_element_path']}/{$data['name']}", "{$g['captiveportal_path']}/{$data['name']}");
1630
			}
1631
		}
1632
		conf_mount_ro();
1633
	}
1634

    
1635
	return 0;
1636
}
1637

    
1638
function captiveportal_free_dnrules($rulenos_start = 2000, $rulenos_range_max = 64500) {
1639
	global $cpzone;
1640

    
1641
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1642
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1643
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1644
		$ridx = $rulenos_start;
1645
		while ($ridx < $rulenos_range_max) {
1646
			if ($rules[$ridx] == $cpzone) {
1647
				$rules[$ridx] = false;
1648
				$ridx++;
1649
				$rules[$ridx] = false;
1650
				$ridx++;
1651
			} else {
1652
				$ridx += 2;
1653
			}
1654
		}
1655
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1656
		unset($rules);
1657
	}
1658
	unlock($cpruleslck);
1659
}
1660

    
1661
function captiveportal_get_next_dn_ruleno($rulenos_start = 2000, $rulenos_range_max = 64500) {
1662
	global $config, $g, $cpzone;
1663

    
1664
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1665
	$ruleno = 0;
1666
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1667
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1668
		$ridx = $rulenos_start;
1669
		while ($ridx < $rulenos_range_max) {
1670
			if (empty($rules[$ridx])) {
1671
				$ruleno = $ridx;
1672
				$rules[$ridx] = $cpzone;
1673
				$ridx++;
1674
				$rules[$ridx] = $cpzone;
1675
				break;
1676
			} else {
1677
				$ridx += 2;
1678
			}
1679
		}
1680
	} else {
1681
		$rules = array_pad(array(), $rulenos_range_max, false);
1682
		$ruleno = $rulenos_start;
1683
		$rules[$rulenos_start] = $cpzone;
1684
		$rulenos_start++;
1685
		$rules[$rulenos_start] = $cpzone;
1686
	}
1687
	file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1688
	unlock($cpruleslck);
1689
	unset($rules);
1690

    
1691
	return $ruleno;
1692
}
1693

    
1694
function captiveportal_free_dn_ruleno($ruleno) {
1695
	global $config, $g;
1696

    
1697
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1698
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1699
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1700
		$rules[$ruleno] = false;
1701
		$ruleno++;
1702
		$rules[$ruleno] = false;
1703
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1704
		unset($rules);
1705
	}
1706
	unlock($cpruleslck);
1707
}
1708

    
1709
function captiveportal_get_dn_passthru_ruleno($value) {
1710
	global $config, $g, $cpzone, $cpzoneid;
1711

    
1712
	$cpcfg = $config['captiveportal'][$cpzone];
1713
	if (!isset($cpcfg['enable'])) {
1714
		return NULL;
1715
	}
1716

    
1717
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1718
	$ruleno = NULL;
1719
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1720
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1721
		unset($output);
1722
		$_gb = exec("/sbin/ipfw -x {$cpzoneid} show | /usr/bin/grep " . escapeshellarg($value) . " | /usr/bin/grep -v grep | /usr/bin/awk '{print $5}' | /usr/bin/head -n 1", $output);
1723
		$ruleno = intval($output[0]);
1724
		if (!$rules[$ruleno]) {
1725
			$ruleno = NULL;
1726
		}
1727
		unset($rules);
1728
	}
1729
	unlock($cpruleslck);
1730

    
1731
	return $ruleno;
1732
}
1733

    
1734
/*
1735
 * This function will calculate the lowest free firewall ruleno
1736
 * within the range specified based on the actual logged on users
1737
 *
1738
 */
1739
function captiveportal_get_next_ipfw_ruleno($rulenos_start = 2, $rulenos_range_max = 64500) {
1740
	global $config, $g, $cpzone;
1741

    
1742
	$cpcfg = $config['captiveportal'][$cpzone];
1743
	if (!isset($cpcfg['enable'])) {
1744
		return NULL;
1745
	}
1746

    
1747
	$cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX);
1748
	$ruleno = 0;
1749
	if (file_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules")) {
1750
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules"));
1751
		$ridx = $rulenos_start;
1752
		while ($ridx < $rulenos_range_max) {
1753
			if (empty($rules[$ridx])) {
1754
				$ruleno = $ridx;
1755
				$rules[$ridx] = $cpzone;
1756
				$ridx++;
1757
				$rules[$ridx] = $cpzone;
1758
				break;
1759
			} else {
1760
				/*
1761
				 * This allows our traffic shaping pipes to be the in pipe the same as ruleno
1762
				 * and the out pipe ruleno + 1.
1763
				 */
1764
				$ridx += 2;
1765
			}
1766
		}
1767
	} else {
1768
		$rules = array_pad(array(), $rulenos_range_max, false);
1769
		$ruleno = $rulenos_start;
1770
		$rules[$rulenos_start] = $cpzone;
1771
		$rulenos_start++;
1772
		$rules[$rulenos_start] = $cpzone;
1773
	}
1774
	file_put_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules", serialize($rules));
1775
	unlock($cpruleslck);
1776
	unset($rules);
1777

    
1778
	return $ruleno;
1779
}
1780

    
1781
function captiveportal_free_ipfw_ruleno($ruleno) {
1782
	global $config, $g, $cpzone;
1783

    
1784
	$cpcfg = $config['captiveportal'][$cpzone];
1785
	if (!isset($cpcfg['enable'])) {
1786
		return NULL;
1787
	}
1788

    
1789
	$cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX);
1790
	if (file_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules")) {
1791
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules"));
1792
		$rules[$ruleno] = false;
1793
		$ruleno++;
1794
		$rules[$ruleno] = false;
1795
		file_put_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules", serialize($rules));
1796
		unset($rules);
1797
	}
1798
	unlock($cpruleslck);
1799
}
1800

    
1801
function captiveportal_get_ipfw_passthru_ruleno($value) {
1802
	global $config, $g, $cpzone, $cpzoneid;
1803

    
1804
	$cpcfg = $config['captiveportal'][$cpzone];
1805
	if (!isset($cpcfg['enable'])) {
1806
		return NULL;
1807
	}
1808

    
1809
	$cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX);
1810
	$ruleno = NULL;
1811
	if (file_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules")) {
1812
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules"));
1813
		unset($output);
1814
		$_gb = exec("/sbin/ipfw -x {$cpzoneid} show | /usr/bin/grep " . escapeshellarg($value) . " | /usr/bin/grep -v grep | /usr/bin/awk '{print $1}' | /usr/bin/head -n 1", $output);
1815
		$ruleno = intval($output[0]);
1816
		if (!$rules[$ruleno]) {
1817
			$ruleno = NULL;
1818
		}
1819
		unset($rules);
1820
	}
1821
	unlock($cpruleslck);
1822

    
1823
	return $ruleno;
1824
}
1825

    
1826
/**
1827
 * This function will calculate the traffic produced by a client
1828
 * based on its firewall rule
1829
 *
1830
 * Point of view: NAS
1831
 *
1832
 * Input means: from the client
1833
 * Output means: to the client
1834
 *
1835
 */
1836

    
1837
function getVolume($ip, $mac = NULL) {
1838
	global $config, $cpzone, $cpzoneid;
1839

    
1840
	$reverse = isset($config['captiveportal'][$cpzone]['reverseacct']) ? true : false;
1841
	$volume = array();
1842
	// Initialize vars properly, since we don't want NULL vars
1843
	$volume['input_pkts'] = $volume['input_bytes'] = $volume['output_pkts'] = $volume['output_bytes'] = 0 ;
1844

    
1845
	$ipfw = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, 1, $ip, $mac);
1846
	if (is_array($ipfw)) {
1847
		if ($reverse) {
1848
			$volume['output_pkts'] = $ipfw['packets'];
1849
			$volume['output_bytes'] = $ipfw['bytes'];
1850
		}
1851
		else {
1852
			$volume['input_pkts'] = $ipfw['packets'];
1853
			$volume['input_bytes'] = $ipfw['bytes'];
1854
		}
1855
	}
1856

    
1857
	$ipfw = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, 2, $ip, $mac);
1858
	if (is_array($ipfw)) {
1859
		if ($reverse) {
1860
			$volume['input_pkts'] = $ipfw['packets'];
1861
			$volume['input_bytes'] = $ipfw['bytes'];
1862
		}
1863
		else {
1864
			$volume['output_pkts'] = $ipfw['packets'];
1865
			$volume['output_bytes'] = $ipfw['bytes'];
1866
		}
1867
	}
1868

    
1869
	return $volume;
1870
}
1871

    
1872
/**
1873
 * Get the NAS-IP-Address based on the current wan address
1874
 *
1875
 * Use functions in interfaces.inc to find this out
1876
 *
1877
 */
1878

    
1879
function getNasIP() {
1880
	global $config, $cpzone;
1881

    
1882
	if (empty($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1883
			$nasIp = get_interface_ip();
1884
	} else {
1885
		if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1886
			$nasIp = $config['captiveportal'][$cpzone]['radiussrcip_attribute'];
1887
		} else {
1888
			$nasIp = get_interface_ip($config['captiveportal'][$cpzone]['radiussrcip_attribute']);
1889
		}
1890
	}
1891

    
1892
	if (!is_ipaddr($nasIp)) {
1893
		$nasIp = "0.0.0.0";
1894
	}
1895

    
1896
	return $nasIp;
1897
}
1898

    
1899
function portal_ip_from_client_ip($cliip) {
1900
	global $config, $cpzone;
1901

    
1902
	$isipv6 = is_ipaddrv6($cliip);
1903
	$interfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
1904
	foreach ($interfaces as $cpif) {
1905
		if ($isipv6) {
1906
			$ip = get_interface_ipv6($cpif);
1907
			$sn = get_interface_subnetv6($cpif);
1908
		} else {
1909
			$ip = get_interface_ip($cpif);
1910
			$sn = get_interface_subnet($cpif);
1911
		}
1912
		if (ip_in_subnet($cliip, "{$ip}/{$sn}")) {
1913
			return $ip;
1914
		}
1915
	}
1916

    
1917
	$inet = ($isipv6) ? '-inet6' : '-inet';
1918
	$iface = exec_command("/sbin/route -n get {$inet} {$cliip} | /usr/bin/awk '/interface/ { print \$2; };'");
1919
	$iface = trim($iface, "\n");
1920
	if (!empty($iface)) {
1921
		$ip = ($isipv6) ? find_interface_ipv6($iface) : find_interface_ip($iface);
1922
		if (is_ipaddr($ip)) {
1923
			return $ip;
1924
		}
1925
	}
1926

    
1927
	// doesn't match up to any particular interface
1928
	// so let's set the portal IP to what PHP says
1929
	// the server IP issuing the request is.
1930
	// allows same behavior as 1.2.x where IP isn't
1931
	// in the subnet of any CP interface (static routes, etc.)
1932
	// rather than forcing to DNS hostname resolution
1933
	$ip = $_SERVER['SERVER_ADDR'];
1934
	if (is_ipaddr($ip)) {
1935
		return $ip;
1936
	}
1937

    
1938
	return false;
1939
}
1940

    
1941
function portal_hostname_from_client_ip($cliip) {
1942
	global $config, $cpzone;
1943

    
1944
	$cpcfg = $config['captiveportal'][$cpzone];
1945

    
1946
	if (isset($cpcfg['httpslogin'])) {
1947
		$listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 8001);
1948
		$ourhostname = $cpcfg['httpsname'];
1949

    
1950
		if ($listenporthttps != 443) {
1951
			$ourhostname .= ":" . $listenporthttps;
1952
		}
1953
	} else {
1954
		$listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : ($cpcfg['zoneid'] + 8000);
1955
		$ifip = portal_ip_from_client_ip($cliip);
1956
		if (!$ifip) {
1957
			$ourhostname = "{$config['system']['hostname']}.{$config['system']['domain']}";
1958
		} else {
1959
			$ourhostname = (is_ipaddrv6($ifip)) ? "[{$ifip}]" : "{$ifip}";
1960
		}
1961

    
1962
		if ($listenporthttp != 80) {
1963
			$ourhostname .= ":" . $listenporthttp;
1964
		}
1965
	}
1966

    
1967
	return $ourhostname;
1968
}
1969

    
1970
/* functions move from index.php */
1971

    
1972
function portal_reply_page($redirurl, $type = null, $message = null, $clientmac = null, $clientip = null, $username = null, $password = null) {
1973
	global $g, $config, $cpzone;
1974

    
1975
	/* Get captive portal layout */
1976
	if ($type == "redir") {
1977
		header("Location: {$redirurl}");
1978
		return;
1979
	} else if ($type == "login") {
1980
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
1981
	} else {
1982
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
1983
	}
1984

    
1985
	$cpcfg = $config['captiveportal'][$cpzone];
1986

    
1987
	/* substitute the PORTAL_REDIRURL variable */
1988
	if ($cpcfg['preauthurl']) {
1989
		$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
1990
		$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
1991
	}
1992

    
1993
	/* substitute other variables */
1994
	$ourhostname = portal_hostname_from_client_ip($clientip);
1995
	$protocol = (isset($cpcfg['httpslogin'])) ? 'https://' : 'http://';
1996
	$htmltext = str_replace("\$PORTAL_ACTION\$", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
1997
	$htmltext = str_replace("#PORTAL_ACTION#", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
1998

    
1999
	$htmltext = str_replace("\$PORTAL_ZONE\$", htmlspecialchars($cpzone), $htmltext);
2000
	$htmltext = str_replace("\$PORTAL_REDIRURL\$", htmlspecialchars($redirurl), $htmltext);
2001
	$htmltext = str_replace("\$PORTAL_MESSAGE\$", htmlspecialchars($message), $htmltext);
2002
	$htmltext = str_replace("\$CLIENT_MAC\$", htmlspecialchars($clientmac), $htmltext);
2003
	$htmltext = str_replace("\$CLIENT_IP\$", htmlspecialchars($clientip), $htmltext);
2004

    
2005
	// Special handling case for captive portal master page so that it can be ran
2006
	// through the PHP interpreter using the include method above.  We convert the
2007
	// $VARIABLE$ case to #VARIABLE# in /etc/inc/captiveportal.inc before writing out.
2008
	$htmltext = str_replace("#PORTAL_ZONE#", htmlspecialchars($cpzone), $htmltext);
2009
	$htmltext = str_replace("#PORTAL_REDIRURL#", htmlspecialchars($redirurl), $htmltext);
2010
	$htmltext = str_replace("#PORTAL_MESSAGE#", htmlspecialchars($message), $htmltext);
2011
	$htmltext = str_replace("#CLIENT_MAC#", htmlspecialchars($clientmac), $htmltext);
2012
	$htmltext = str_replace("#CLIENT_IP#", htmlspecialchars($clientip), $htmltext);
2013
	$htmltext = str_replace("#USERNAME#", htmlspecialchars($username), $htmltext);
2014
	$htmltext = str_replace("#PASSWORD#", htmlspecialchars($password), $htmltext);
2015

    
2016
	echo $htmltext;
2017
}
2018

    
2019
function portal_mac_radius($clientmac, $clientip) {
2020
	global $config, $cpzone;
2021

    
2022
	$radmac_secret = $config['captiveportal'][$cpzone]['radmac_secret'];
2023

    
2024
	/* authentication against the radius server */
2025
	$username = mac_format($clientmac);
2026
	$auth_list = radius($username, $radmac_secret, $clientip, $clientmac, "MACHINE LOGIN");
2027
	if ($auth_list['auth_val'] == 2) {
2028
		return TRUE;
2029
	}
2030

    
2031
	if (!empty($auth_list['url_redirection'])) {
2032
		portal_reply_page($auth_list['url_redirection'], "redir");
2033
	}
2034

    
2035
	return FALSE;
2036
}
2037

    
2038
function captiveportal_reapply_attributes($cpentry, $attributes) {
2039
	global $config, $cpzone, $g;
2040

    
2041
	if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2042
		$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2043
		$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2044
	} else {
2045
		$dwfaultbw_up = $dwfaultbw_down = 0;
2046
	}
2047
	$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2048
	$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2049
	$bw_up_pipeno = $cpentry[1];
2050
	$bw_down_pipeno = $cpentry[1]+1;
2051

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

    
2056
	unset($bw_up_pipeno, $bw_down_pipeno, $bw_up, $bw_down);
2057
}
2058

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

    
2062
	// Ensure we create an array if we are missing attributes
2063
	if (!is_array($attributes)) {
2064
		$attributes = array();
2065
	}
2066

    
2067
	unset($sessionid);
2068

    
2069
	/* Do not allow concurrent login execution. */
2070
	$cpdblck = lock("captiveportaldb{$cpzone}", LOCK_EX);
2071

    
2072
	if ($attributes['voucher']) {
2073
		$remaining_time = $attributes['session_timeout'];
2074
	// Set RADIUS-Attribute to Voucher to prevent ReAuth-Reqeuest for Vouchers Bug: #2155
2075
		$radiusctx="voucher";
2076
	}
2077

    
2078
	$writecfg = false;
2079
	/* Find an existing session */
2080
	if ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && $passthrumac) {
2081
		if (isset($config['captiveportal'][$cpzone]['passthrumacadd'])) {
2082
			$mac = captiveportal_passthrumac_findbyname($username);
2083
			if (!empty($mac)) {
2084
				if ($_POST['replacemacpassthru']) {
2085
					foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $idx => $macent) {
2086
						if ($macent['mac'] == $mac['mac']) {
2087
							$macrules = "";
2088
							$ruleno = captiveportal_get_ipfw_passthru_ruleno($mac['mac']);
2089
							$pipeno = captiveportal_get_dn_passthru_ruleno($mac['mac']);
2090
							if ($ruleno) {
2091
								captiveportal_free_ipfw_ruleno($ruleno);
2092
								$macrules .= "delete {$ruleno}\n";
2093
								++$ruleno;
2094
								$macrules .= "delete {$ruleno}\n";
2095
							}
2096
							if ($pipeno) {
2097
								captiveportal_free_dn_ruleno($pipeno);
2098
								$macrules .= "pipe delete {$pipeno}\n";
2099
								++$pipeno;
2100
								$macrules .= "pipe delete {$pipeno}\n";
2101
							}
2102
							unset($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
2103
							$mac['action'] = 'pass';
2104
							$mac['mac'] = $clientmac;
2105
							$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2106
							$macrules .= captiveportal_passthrumac_configure_entry($mac);
2107
							file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2108
							mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2109
							$writecfg = true;
2110
							$sessionid = true;
2111
							break;
2112
						}
2113
					}
2114
				} else {
2115
					portal_reply_page($redirurl, "error", "Username: {$username} is already authenticated using another MAC address.",
2116
						$clientmac, $clientip, $username, $password);
2117
					unlock($cpdblck);
2118
					return;
2119
				}
2120
			}
2121
		}
2122
	}
2123

    
2124
	/* read in client database */
2125
	$query = "WHERE ip = '{$clientip}'";
2126
	$tmpusername = SQLite3::escapeString(strtolower($username));
2127
	if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
2128
		$query .= " OR (username != 'unauthenticated' AND lower(username) = '{$tmpusername}')";
2129
	}
2130
	$cpdb = captiveportal_read_db($query);
2131

    
2132
	/* Snapshot the timestamp */
2133
	$allow_time = time();
2134
	$radiusservers = captiveportal_get_radius_servers();
2135
	$unsetindexes = array();
2136
	if (is_null($radiusctx)) {
2137
		$radiusctx = 'first';
2138
	}
2139

    
2140
	foreach ($cpdb as $cpentry) {
2141
		if (empty($cpentry[11])) {
2142
			$cpentry[11] = 'first';
2143
		}
2144
		/* on the same ip */
2145
		if ($cpentry[2] == $clientip) {
2146
			if (isset($config['captiveportal'][$cpzone]['nomacfilter']) || $cpentry[3] == $clientmac) {
2147
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING OLD SESSION");
2148
			} else {
2149
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING IP {$cpentry[2]} WITH DIFFERENT MAC ADDRESS {$cpentry[3]}");
2150
			}
2151
			$sessionid = $cpentry[5];
2152
			break;
2153
		} elseif (($attributes['voucher']) && ($username != 'unauthenticated') && ($cpentry[4] == $username)) {
2154
			// user logged in with an active voucher. Check for how long and calculate
2155
			// how much time we can give him (voucher credit - used time)
2156
			$remaining_time = $cpentry[0] + $cpentry[7] - $allow_time;
2157
			if ($remaining_time < 0) { // just in case.
2158
				$remaining_time = 0;
2159
			}
2160

    
2161
			/* This user was already logged in so we disconnect the old one */
2162
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2163
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2164
			$unsetindexes[] = $cpentry[5];
2165
			break;
2166
		} elseif ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && ($username != 'unauthenticated')) {
2167
			/* on the same username */
2168
			if (strcasecmp($cpentry[4], $username) == 0) {
2169
				/* This user was already logged in so we disconnect the old one */
2170
				captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2171
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2172
				$unsetindexes[] = $cpentry[5];
2173
				break;
2174
			}
2175
		}
2176
	}
2177
	unset($cpdb);
2178

    
2179
	if (!empty($unsetindexes)) {
2180
		captiveportal_remove_entries($unsetindexes);
2181
	}
2182

    
2183
	if ($attributes['voucher'] && $remaining_time <= 0) {
2184
		return 0;       // voucher already used and no time left
2185
	}
2186

    
2187
	if (!isset($sessionid)) {
2188
		/* generate unique session ID */
2189
		$tod = gettimeofday();
2190
		$sessionid = substr(md5(mt_rand() . $tod['sec'] . $tod['usec'] . $clientip . $clientmac), 0, 16);
2191

    
2192
		if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2193
			$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2194
			$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2195
		} else {
2196
			$dwfaultbw_up = $dwfaultbw_down = 0;
2197
		}
2198
		$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2199
		$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2200

    
2201
		if ($passthrumac) {
2202
			$mac = array();
2203
			$mac['action'] = 'pass';
2204
			$mac['mac'] = $clientmac;
2205
			$mac['ip'] = $clientip; /* Used only for logging */
2206
			if (isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
2207
				$mac['username'] = $username;
2208
				if ($attributes['voucher']) {
2209
					$mac['logintype'] = "voucher";
2210
				}
2211
			}
2212
			if ($username == "unauthenticated") {
2213
				$mac['descr'] = "Auto-added";
2214
			} else {
2215
				$mac['descr'] = "Auto-added for user {$username}";
2216
			}
2217
			if (!empty($bw_up)) {
2218
				$mac['bw_up'] = $bw_up;
2219
			}
2220
			if (!empty($bw_down)) {
2221
				$mac['bw_down'] = $bw_down;
2222
			}
2223
			if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2224
				$config['captiveportal'][$cpzone]['passthrumac'] = array();
2225
			}
2226
			$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2227
			unlock($cpdblck);
2228
			$macrules = captiveportal_passthrumac_configure_entry($mac);
2229
			file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2230
			mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2231
			$writecfg = true;
2232
		} else {
2233
			/* See if a pipeno is passed, if not start sessions because this means there isn't one atm */
2234
			if (is_null($pipeno)) {
2235
				$pipeno = captiveportal_get_next_dn_ruleno();
2236
			}
2237

    
2238
			/* if the pool is empty, return appropriate message and exit */
2239
			if (is_null($pipeno)) {
2240
				portal_reply_page($redirurl, "error", "System reached maximum login capacity");
2241
				log_error("Zone: {$cpzone} - WARNING!  Captive portal has reached maximum login capacity");
2242
				unlock($cpdblck);
2243
				return;
2244
			}
2245

    
2246
			$bw_up_pipeno = $pipeno;
2247
			$bw_down_pipeno = $pipeno + 1;
2248
			//$bw_up /= 1000; // Scale to Kbit/s
2249
			$_gb = @pfSense_pipe_action("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2250
			$_gb = @pfSense_pipe_action("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2251

    
2252
			$clientsn = (is_ipaddrv6($clientip)) ? 128 : 32;
2253
			if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) {
2254
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 1, $clientip, $clientsn, $clientmac, $bw_up_pipeno);
2255
			} else {
2256
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 1, $clientip, $clientsn, NULL, $bw_up_pipeno);
2257
			}
2258

    
2259
			if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) {
2260
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 2, $clientip, $clientsn, $clientmac, $bw_down_pipeno);
2261
			} else {
2262
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 2, $clientip, $clientsn, NULL, $bw_down_pipeno);
2263
			}
2264

    
2265
			if ($attributes['voucher']) {
2266
				$attributes['session_timeout'] = $remaining_time;
2267
			}
2268

    
2269
			/* handle empty attributes */
2270
			$session_timeout = (!empty($attributes['session_timeout'])) ? $attributes['session_timeout'] : 'NULL';
2271
			$idle_timeout = (!empty($attributes['idle_timeout'])) ? $attributes['idle_timeout'] : 'NULL';
2272
			$session_terminate_time = (!empty($attributes['session_terminate_time'])) ? $attributes['session_terminate_time'] : 'NULL';
2273
			$interim_interval = (!empty($attributes['interim_interval'])) ? $attributes['interim_interval'] : 'NULL';
2274

    
2275
			/* escape username */
2276
			$safe_username = SQLite3::escapeString($username);
2277

    
2278
			/* encode password in Base64 just in case it contains commas */
2279
			$bpassword = (isset($config['captiveportal'][$cpzone]['reauthenticate'])) ? base64_encode($password) : '';
2280
			$insertquery = "INSERT INTO captiveportal (allow_time, pipeno, ip, mac, username, sessionid, bpassword, session_timeout, idle_timeout, session_terminate_time, interim_interval, radiusctx) ";
2281
			$insertquery .= "VALUES ({$allow_time}, {$pipeno}, '{$clientip}', '{$clientmac}', '{$safe_username}', '{$sessionid}', '{$bpassword}', ";
2282
			$insertquery .= "{$session_timeout}, {$idle_timeout}, {$session_terminate_time}, {$interim_interval}, '{$radiusctx}')";
2283

    
2284
			/* store information to database */
2285
			captiveportal_write_db($insertquery);
2286
			unlock($cpdblck);
2287
			unset($insertquery, $bpassword);
2288

    
2289
			if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers[$radiusctx])) {
2290
				$acct_val = RADIUS_ACCOUNTING_START($pipeno, $username, $sessionid, $radiusservers[$radiusctx], $clientip, $clientmac);
2291
				if ($acct_val == 1) {
2292
					captiveportal_logportalauth($username, $clientmac, $clientip, $type, "RADIUS ACCOUNTING FAILED");
2293
				}
2294
			}
2295
		}
2296
	} else {
2297
		/* NOTE: #3062-11 If the pipeno has been allocated free it to not DoS the CP and maintain proper operation as in radius() case */
2298
		if (!is_null($pipeno)) {
2299
			captiveportal_free_dn_ruleno($pipeno);
2300
		}
2301

    
2302
		unlock($cpdblck);
2303
	}
2304

    
2305
	if ($writecfg == true) {
2306
		write_config();
2307
	}
2308

    
2309
	/* redirect user to desired destination */
2310
	if (!empty($attributes['url_redirection'])) {
2311
		$my_redirurl = $attributes['url_redirection'];
2312
	} else if (!empty($redirurl)) {
2313
		$my_redirurl = $redirurl;
2314
	} else if (!empty($config['captiveportal'][$cpzone]['redirurl'])) {
2315
		$my_redirurl = $config['captiveportal'][$cpzone]['redirurl'];
2316
	}
2317

    
2318
	if (isset($config['captiveportal'][$cpzone]['logoutwin_enable']) && !$passthrumac) {
2319
		$ourhostname = portal_hostname_from_client_ip($clientip);
2320
		$protocol = (isset($config['captiveportal'][$cpzone]['httpslogin'])) ? 'https://' : 'http://';
2321
		$logouturl = "{$protocol}{$ourhostname}/";
2322

    
2323
		if (isset($attributes['reply_message'])) {
2324
			$message = $attributes['reply_message'];
2325
		} else {
2326
			$message = 0;
2327
		}
2328

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

    
2331
	} else {
2332
		portal_reply_page($my_redirurl, "redir", "Just redirect the user.");
2333
	}
2334

    
2335
	return $sessionid;
2336
}
2337

    
2338

    
2339
/*
2340
 * Used for when pass-through credits are enabled.
2341
 * Returns true when there was at least one free login to deduct for the MAC.
2342
 * Expired entries are removed as they are seen.
2343
 * Active entries are updated according to the configuration.
2344
 */
2345
function portal_consume_passthrough_credit($clientmac) {
2346
	global $config, $cpzone;
2347

    
2348
	if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count'])) {
2349
		$freeloginscount = $config['captiveportal'][$cpzone]['freelogins_count'];
2350
	} else {
2351
		return false;
2352
	}
2353

    
2354
	if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout'])) {
2355
		$resettimeout = $config['captiveportal'][$cpzone]['freelogins_resettimeout'];
2356
	} else {
2357
		return false;
2358
	}
2359

    
2360
	if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac) {
2361
		return false;
2362
	}
2363

    
2364
	$updatetimeouts = isset($config['captiveportal'][$cpzone]['freelogins_updatetimeouts']);
2365

    
2366
	/*
2367
	 * Read database of used MACs.  Lines are a comma-separated list
2368
	 * of the time, MAC, then the count of pass-through credits remaining.
2369
	 */
2370
	$usedmacs = captiveportal_read_usedmacs_db();
2371

    
2372
	$currenttime = time();
2373
	$found = false;
2374
	foreach ($usedmacs as $key => $usedmac) {
2375
		$usedmac = explode(",", $usedmac);
2376

    
2377
		if ($usedmac[1] == $clientmac) {
2378
			if ($usedmac[0] + ($resettimeout * 3600) > $currenttime) {
2379
				if ($usedmac[2] < 1) {
2380
					if ($updatetimeouts) {
2381
						$usedmac[0] = $currenttime;
2382
						unset($usedmacs[$key]);
2383
						$usedmacs[] = implode(",", $usedmac);
2384
						captiveportal_write_usedmacs_db($usedmacs);
2385
					}
2386

    
2387
					return false;
2388
				} else {
2389
					$usedmac[2] -= 1;
2390
					$usedmacs[$key] = implode(",", $usedmac);
2391
				}
2392

    
2393
				$found = true;
2394
			} else {
2395
				unset($usedmacs[$key]);
2396
			}
2397

    
2398
			break;
2399
		} else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime) {
2400
			unset($usedmacs[$key]);
2401
		}
2402
	}
2403

    
2404
	if (!$found) {
2405
		$usedmac = array($currenttime, $clientmac, $freeloginscount - 1);
2406
		$usedmacs[] = implode(",", $usedmac);
2407
	}
2408

    
2409
	captiveportal_write_usedmacs_db($usedmacs);
2410
	return true;
2411
}
2412

    
2413
function captiveportal_read_usedmacs_db() {
2414
	global $g, $cpzone;
2415

    
2416
	$cpumaclck = lock("captiveusedmacs{$cpzone}");
2417
	if (file_exists("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db")) {
2418
		$usedmacs = file("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2419
		if (!$usedmacs) {
2420
			$usedmacs = array();
2421
		}
2422
	} else {
2423
		$usedmacs = array();
2424
	}
2425

    
2426
	unlock($cpumaclck);
2427
	return $usedmacs;
2428
}
2429

    
2430
function captiveportal_write_usedmacs_db($usedmacs) {
2431
	global $g, $cpzone;
2432

    
2433
	$cpumaclck = lock("captiveusedmacs{$cpzone}", LOCK_EX);
2434
	@file_put_contents("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", implode("\n", $usedmacs));
2435
	unlock($cpumaclck);
2436
}
2437

    
2438
function captiveportal_blocked_mac($mac) {
2439
	global $config, $g, $cpzone;
2440

    
2441
	if (empty($mac) || !is_macaddr($mac)) {
2442
		return false;
2443
	}
2444

    
2445
	if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2446
		return false;
2447
	}
2448

    
2449
	foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) {
2450
		if (($passthrumac['action'] == 'block') &&
2451
		    ($passthrumac['mac'] == strtolower($mac))) {
2452
			return true;
2453
		}
2454
	}
2455

    
2456
	return false;
2457

    
2458
}
2459

    
2460
function captiveportal_send_server_accounting($off = false) {
2461
	global $cpzone, $config;
2462

    
2463
	if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
2464
		return;
2465
	}
2466
	if ($off) {
2467
		$racct = new Auth_RADIUS_Acct_Off;
2468
	} else {
2469
		$racct = new Auth_RADIUS_Acct_On;
2470
	}
2471
	$radiusservers = captiveportal_get_radius_servers();
2472
	if (empty($radiusservers)) {
2473
		return;
2474
	}
2475
	foreach ($radiusservers['first'] as $radsrv) {
2476
		// Add a new server to our instance
2477
		$racct->addServer($radsrv['ipaddr'], $radsrv['acctport'], $radsrv['key']);
2478
	}
2479
	if (PEAR::isError($racct->start())) {
2480
		$retvalue['acct_val'] = 1;
2481
		$retvalue['error'] = $racct->getMessage();
2482

    
2483
		// If we encounter an error immediately stop this function and go back
2484
		$racct->close();
2485
		return $retvalue;
2486
	}
2487
	// Send request
2488
	$result = $racct->send();
2489
	// Evaluation of the response
2490
	// 5 -> Accounting-Response
2491
	// See RFC2866 for this.
2492
	if (PEAR::isError($result)) {
2493
		$retvalue['acct_val'] = 1;
2494
		$retvalue['error'] = $result->getMessage();
2495
	} else if ($result === true) {
2496
		$retvalue['acct_val'] = 5 ;
2497
	} else {
2498
		$retvalue['acct_val'] = 1 ;
2499
	}
2500

    
2501
	$racct->close();
2502
	return $retvalue;
2503
}
2504

    
2505
function captiveportal_isip_logged($clientip) {
2506
	global $g, $cpzone;
2507

    
2508
	/* read in client database */
2509
	$query = "WHERE ip = '{$clientip}'";
2510
	$cpdb = captiveportal_read_db($query);
2511
	foreach ($cpdb as $cpentry) {
2512
		return $cpentry;
2513
	}
2514
}
2515
?>
(9-9/67)