Project

General

Profile

Download (83.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * captiveportal.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2018 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
 * Licensed under the Apache License, Version 2.0 (the "License");
14
 * you may not use this file except in compliance with the License.
15
 * You may obtain a copy of the License at
16
 *
17
 * http://www.apache.org/licenses/LICENSE-2.0
18
 *
19
 * Unless required by applicable law or agreed to in writing, software
20
 * distributed under the License is distributed on an "AS IS" BASIS,
21
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
 * See the License for the specific language governing permissions and
23
 * limitations under the License.
24
 */
25

    
26
/* include all configuration functions */
27
require_once("config.inc");
28
require_once("functions.inc");
29
require_once("filter.inc");
30
require_once("radius.inc");
31
require_once("voucher.inc");
32

    
33
function get_default_captive_portal_html() {
34
	global $config, $g, $cpzone;
35

    
36
	$translated_text1 = sprintf(gettext("%s captive portal"), $g['product_name']);
37
	$translated_text2 = sprintf(gettext("Welcome to the %s Captive Portal!"), $g['product_name']);
38
	$translated_text3 = gettext("Username:");
39
	$translated_text4 = gettext("Password:");
40
	$htmltext = <<<EOD
41
<html>
42
<body>
43
<form method="post" action="\$PORTAL_ACTION\$">
44
	<input name="redirurl" type="hidden" value="\$PORTAL_REDIRURL\$">
45
	<input name="zone" type="hidden" value="\$PORTAL_ZONE\$">
46
	<center>
47
	<table cellpadding="6" cellspacing="0" width="550" height="380" style="border:1px solid #000000">
48
	<tr height="10" style="background-color:#990000">
49
		<td style="border-bottom:1px solid #000000">
50
			<font color='white'>
51
			<b>
52
				{$translated_text1}
53
			</b>
54
			</font>
55
		</td>
56
	</tr>
57
	<tr>
58
		<td>
59
			<div id="mainlevel">
60
			<center>
61
			<table width="100%" border="0" cellpadding="5" cellspacing="0">
62
			<tr>
63
				<td>
64
					<center>
65
					<div id="mainarea">
66
					<center>
67
					<table width="100%" border="0" cellpadding="5" cellspacing="5">
68
					<tr>
69
						<td>
70
							<div id="maindivarea">
71
							<center>
72
								<div id='statusbox'>
73
									<font color='red' face='arial' size='+1'>
74
									<b>
75
										\$PORTAL_MESSAGE\$
76
									</b>
77
									</font>
78
								</div>
79
								<br />
80
								<div id='loginbox'>
81
								<table>
82
									<tr><td colspan="2"><center>{$translated_text2}</td></tr>
83
									<tr><td>&nbsp;</td></tr>
84
									<tr><td class="text-right">{$translated_text3}</td><td><input name="auth_user" type="text" style="border: 1px dashed;"></td></tr>
85
									<tr><td class="text-right">{$translated_text4}</td><td><input name="auth_pass" type="password" style="border: 1px dashed;"></td></tr>
86
									<tr><td>&nbsp;</td></tr>
87

    
88
EOD;
89

    
90
	if (isset($config['voucher'][$cpzone]['enable'])) {
91
		$translated_text = gettext("Enter Voucher Code:");
92
		$htmltext .= <<<EOD
93
									<tr>
94
										<td class="text-right">{$translated_text} </td>
95
										<td><input name="auth_voucher" type="text" style="border:1px dashed;" size="22"></td>
96
									</tr>
97

    
98
EOD;
99
	}
100

    
101
	$translated_text = gettext("Continue");
102
	$htmltext .= <<<EOD
103
									<tr>
104
										<td colspan="2"><center><input name="accept" type="submit" value="{$translated_text}"></center></td>
105
									</tr>
106
								</table>
107
								</div>
108
							</center>
109
							</div>
110
						</td>
111
					</tr>
112
					</table>
113
					</center>
114
					</div>
115
					</center>
116
				</td>
117
			</tr>
118
			</table>
119
			</center>
120
			</div>
121
		</td>
122
	</tr>
123
	</table>
124
	</center>
125
</form>
126
</body>
127
</html>
128

    
129
EOD;
130

    
131
	return $htmltext;
132
}
133

    
134
function captiveportal_load_modules() {
135
	global $config;
136

    
137
	mute_kernel_msgs();
138
	if (!is_module_loaded("ipfw.ko")) {
139
		mwexec("/sbin/kldload ipfw");
140
		/* make sure ipfw is not on pfil hooks */
141
		set_sysctl(array(
142
		    "net.inet.ip.pfil.inbound" => "pf",
143
		    "net.inet6.ip6.pfil.inbound" => "pf",
144
		    "net.inet.ip.pfil.outbound" => "pf",
145
		    "net.inet6.ip6.pfil.outbound" => "pf"
146
		));
147
	}
148
	/* Activate layer2 filtering */
149
	set_sysctl(array(
150
	    "net.link.ether.ipfw" => "1",
151
	    "net.inet.ip.fw.one_pass" => "1",
152
	    "net.inet.ip.fw.tables_max" => "65534"
153
	));
154

    
155
	/* Always load dummynet now that even allowed ip and mac passthrough use it. */
156
	if (!is_module_loaded("dummynet.ko")) {
157
		mwexec("/sbin/kldload dummynet");
158
		set_sysctl(array(
159
		    "net.inet.ip.dummynet.io_fast" => "1",
160
		    "net.inet.ip.dummynet.hash_size" => "256"
161
		));
162
	}
163
	unmute_kernel_msgs();
164
}
165

    
166
function captiveportal_configure() {
167
	global $config, $cpzone, $cpzoneid;
168

    
169
	if (is_array($config['captiveportal'])) {
170
		foreach ($config['captiveportal'] as $cpkey => $cp) {
171
			$cpzone = $cpkey;
172
			$cpzoneid = $cp['zoneid'];
173
			captiveportal_configure_zone($cp);
174
		}
175
	}
176
}
177

    
178
function captiveportal_configure_zone($cpcfg) {
179
	global $config, $g, $cpzone, $cpzoneid;
180

    
181
	$captiveportallck = lock("captiveportal{$cpzone}", LOCK_EX);
182

    
183
	if (isset($cpcfg['enable'])) {
184

    
185
		if (platform_booting()) {
186
			echo "Starting captive portal({$cpcfg['zone']})... ";
187

    
188
			/* remove old information */
189
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
190
		} else {
191
			captiveportal_syslog("Reconfiguring captive portal({$cpcfg['zone']}).");
192
		}
193

    
194
		/* init ipfw rules */
195
		captiveportal_init_rules(true);
196

    
197
		/* kill any running minicron */
198
		killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
199

    
200
		/* initialize minicron interval value */
201
		$croninterval = $cpcfg['croninterval'] ? $cpcfg['croninterval'] : 60;
202

    
203
		/* double check if the $croninterval is numeric and at least 10 seconds. If not we set it to 60 to avoid problems */
204
		if ((!is_numeric($croninterval)) || ($croninterval < 10)) {
205
			$croninterval = 60;
206
		}
207

    
208
		/* write portal page */
209
		if (is_array($cpcfg['page']) && $cpcfg['page']['htmltext']) {
210
			$htmltext = base64_decode($cpcfg['page']['htmltext']);
211
		} else {
212
			/* example/template page */
213
			$htmltext = get_default_captive_portal_html();
214
		}
215

    
216
		$fd = @fopen("{$g['varetc_path']}/captiveportal_{$cpzone}.html", "w");
217
		if ($fd) {
218
			// Special case handling.  Convert so that we can pass this page
219
			// through the PHP interpreter later without clobbering the vars.
220
			$htmltext = str_replace("\$PORTAL_ZONE\$", "#PORTAL_ZONE#", $htmltext);
221
			$htmltext = str_replace("\$PORTAL_REDIRURL\$", "#PORTAL_REDIRURL#", $htmltext);
222
			$htmltext = str_replace("\$PORTAL_MESSAGE\$", "#PORTAL_MESSAGE#", $htmltext);
223
			$htmltext = str_replace("\$CLIENT_MAC\$", "#CLIENT_MAC#", $htmltext);
224
			$htmltext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $htmltext);
225
			$htmltext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $htmltext);
226
			if ($cpcfg['preauthurl']) {
227
				$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
228
				$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
229
			}
230
			fwrite($fd, $htmltext);
231
			fclose($fd);
232
		}
233
		unset($htmltext);
234

    
235
		/* write error page */
236
		if (is_array($cpcfg['page']) && $cpcfg['page']['errtext']) {
237
			$errtext = base64_decode($cpcfg['page']['errtext']);
238
		} else {
239
			/* example page  */
240
			$errtext = get_default_captive_portal_html();
241
		}
242

    
243
		$fd = @fopen("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html", "w");
244
		if ($fd) {
245
			// Special case handling.  Convert so that we can pass this page
246
			// through the PHP interpreter later without clobbering the vars.
247
			$errtext = str_replace("\$PORTAL_ZONE\$", "#PORTAL_ZONE#", $errtext);
248
			$errtext = str_replace("\$PORTAL_REDIRURL\$", "#PORTAL_REDIRURL#", $errtext);
249
			$errtext = str_replace("\$PORTAL_MESSAGE\$", "#PORTAL_MESSAGE#", $errtext);
250
			$errtext = str_replace("\$CLIENT_MAC\$", "#CLIENT_MAC#", $errtext);
251
			$errtext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $errtext);
252
			$errtext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $errtext);
253
			if ($cpcfg['preauthurl']) {
254
				$errtext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $errtext);
255
				$errtext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $errtext);
256
			}
257
			fwrite($fd, $errtext);
258
			fclose($fd);
259
		}
260
		unset($errtext);
261

    
262
		/* write logout page */
263
		if (is_array($cpcfg['page']) && $cpcfg['page']['logouttext']) {
264
			$logouttext = base64_decode($cpcfg['page']['logouttext']);
265
		} else {
266
			/* example page */
267
			$translated_text1 = gettext("Redirecting...");
268
			$translated_text2 = gettext("Redirecting to");
269
			$translated_text3 = gettext("Logout");
270
			$translated_text4 = gettext("Click the button below to disconnect");
271
			$logouttext = <<<EOD
272
<html>
273
<head><title>{$translated_text1}</title></head>
274
<body>
275
<span style="font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">
276
<b>{$translated_text2} <a href="<?=\$my_redirurl;?>"><?=\$my_redirurl;?></a>...</b>
277
</span>
278
<script type="text/javascript">
279
//<![CDATA[
280
LogoutWin = window.open('', 'Logout', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=256,height=64');
281
if (LogoutWin) {
282
	LogoutWin.document.write('<html>');
283
	LogoutWin.document.write('<head><title>{$translated_text3}</title></head>') ;
284
	LogoutWin.document.write('<body style="background-color:#435370">');
285
	LogoutWin.document.write('<div class="text-center" style="color: #ffffff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">') ;
286
	LogoutWin.document.write('<b>{$translated_text4}</b><p />');
287
	LogoutWin.document.write('<form method="POST" action="<?=\$logouturl;?>">');
288
	LogoutWin.document.write('<input name="logout_id" type="hidden" value="<?=\$sessionid;?>" />');
289
	LogoutWin.document.write('<input name="zone" type="hidden" value="<?=\$cpzone;?>" />');
290
	LogoutWin.document.write('<input name="logout" type="submit" value="{$translated_text3}" />');
291
	LogoutWin.document.write('</form>');
292
	LogoutWin.document.write('</div></body>');
293
	LogoutWin.document.write('</html>');
294
	LogoutWin.document.close();
295
}
296

    
297
document.location.href="<?=\$my_redirurl;?>";
298
//]]>
299
</script>
300
</body>
301
</html>
302

    
303
EOD;
304
		}
305

    
306
		$fd = @fopen("{$g['varetc_path']}/captiveportal-{$cpzone}-logout.html", "w");
307
		if ($fd) {
308
			fwrite($fd, $logouttext);
309
			fclose($fd);
310
		}
311
		unset($logouttext);
312

    
313
		/* write elements */
314
		captiveportal_write_elements();
315

    
316
		/* kill any running CP nginx instances */
317
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal.pid");
318
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal-SSL.pid");
319

    
320
		/* start up the webserving daemon */
321
		captiveportal_init_webgui_zone($cpcfg);
322

    
323
		/* Kill any existing prunecaptiveportal processes */
324
		if (file_exists("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid")) {
325
			killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
326
		}
327

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

    
332
		/* generate radius server database */
333
		unlink_if_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db");
334
		captiveportal_init_radius_servers();
335

    
336
		if (platform_booting()) {
337
			/* send Accounting-On to server */
338
			captiveportal_send_server_accounting();
339
			echo "done\n";
340
		}
341

    
342
	} else {
343
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal.pid");
344
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal-SSL.pid");
345
		killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
346
		@unlink("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
347
		@unlink("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
348
		@unlink("{$g['varetc_path']}/captiveportal-{$cpzone}-logout.html");
349

    
350
		captiveportal_radius_stop_all(10); // NAS-Request
351

    
352
		captiveportal_filterdns_configure();
353

    
354
		/* remove old information */
355
		unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
356
		unlink_if_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db");
357
		unlink_if_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules");
358
		/* Release allocated pipes for this zone */
359
		$pipes_to_remove = captiveportal_free_dnrules();
360

    
361
		captiveportal_delete_rules($pipes_to_remove);
362

    
363
		if (empty($config['captiveportal'])) {
364
			set_single_sysctl("net.link.ether.ipfw", "0");
365
		} else {
366
			/* Deactivate ipfw(4) if not needed */
367
			$cpactive = false;
368
			if (is_array($config['captiveportal'])) {
369
				foreach ($config['captiveportal'] as $cpkey => $cp) {
370
					if (isset($cp['enable'])) {
371
						$cpactive = true;
372
						break;
373
					}
374
				}
375
			}
376
			if ($cpactive === false) {
377
				set_single_sysctl("net.link.ether.ipfw", "0");
378
			}
379
		}
380
	}
381

    
382
	unlock($captiveportallck);
383

    
384
	return 0;
385
}
386

    
387
function captiveportal_init_webgui() {
388
	global $config, $cpzone;
389

    
390
	if (is_array($config['captiveportal'])) {
391
		foreach ($config['captiveportal'] as $cpkey => $cp) {
392
			$cpzone = $cpkey;
393
			captiveportal_init_webgui_zone($cp);
394
		}
395
	}
396
}
397

    
398
function captiveportal_init_webgui_zonename($zone) {
399
	global $config, $cpzone;
400

    
401
	if (isset($config['captiveportal'][$zone])) {
402
		$cpzone = $zone;
403
		captiveportal_init_webgui_zone($config['captiveportal'][$zone]);
404
	}
405
}
406

    
407
function captiveportal_init_webgui_zone($cpcfg) {
408
	global $g, $config, $cpzone;
409

    
410
	if (!isset($cpcfg['enable'])) {
411
		return;
412
	}
413

    
414
	if (isset($cpcfg['httpslogin'])) {
415
		$cert = lookup_cert($cpcfg['certref']);
416
		$crt = base64_decode($cert['crt']);
417
		$key = base64_decode($cert['prv']);
418
		$ca = ca_chain($cert);
419

    
420
		/* generate nginx configuration */
421
		if (!empty($cpcfg['listenporthttps'])) {
422
			$listenporthttps = $cpcfg['listenporthttps'];
423
		} else {
424
			$listenporthttps = 8001 + $cpcfg['zoneid'];
425
		}
426
		system_generate_nginx_config("{$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal-SSL.conf",
427
			$crt, $key, $ca, "nginx-{$cpzone}-CaptivePortal-SSL.pid", $listenporthttps, "/usr/local/captiveportal",
428
			"cert-{$cpzone}-portal.pem", "ca-{$cpzone}-portal.pem", $cpzone, false);
429
	}
430

    
431
	/* generate nginx configuration */
432
	if (!empty($cpcfg['listenporthttp'])) {
433
		$listenporthttp = $cpcfg['listenporthttp'];
434
	} else {
435
		$listenporthttp = 8000 + $cpcfg['zoneid'];
436
	}
437
	system_generate_nginx_config("{$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal.conf",
438
		"", "", "", "nginx-{$cpzone}-CaptivePortal.pid", $listenporthttp, "/usr/local/captiveportal",
439
		"", "", $cpzone, false);
440

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

    
445
	/* fire up https instance */
446
	if (isset($cpcfg['httpslogin'])) {
447
		@unlink("{$g['varrun']}/nginx-{$cpzone}-CaptivePortal-SSL.pid");
448
		$res = mwexec("/usr/local/sbin/nginx -c {$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal-SSL.conf");
449
	}
450
}
451

    
452
function captiveportal_init_rules_byinterface($interface) {
453
	global $cpzone, $cpzoneid, $config;
454

    
455
	if (!is_array($config['captiveportal'])) {
456
		return;
457
	}
458

    
459
	foreach ($config['captiveportal'] as $cpkey => $cp) {
460
		$cpzone = $cpkey;
461
		$cpzoneid = $cp['zoneid'];
462
		$cpinterfaces = explode(",", $cp['interface']);
463
		if (in_array($interface, $cpinterfaces)) {
464
			captiveportal_init_rules();
465
			break;
466
		}
467
	}
468
}
469

    
470
/* Create basic rules used by all zones */
471
function captiveportal_init_general_rules($flush = false) {
472
	global $g;
473

    
474
	$flush_rule = '';
475
	if ($flush) {
476
		$flush_rule = 'flush';
477
	}
478

    
479
	/* Already loaded */
480
	if (!$flush && (mwexec("/sbin/ipfw list 1000", true) == 0)) {
481
		return;
482
	}
483

    
484
	$cprules = <<<EOD
485
{$flush_rule}
486
# Table with interfaces that have CP enabled
487
table cp_ifaces create type iface valtype skipto
488

    
489
# Redirect each CP interface to its specific rule
490
add 1000 skipto tablearg all from any to any via table(cp_ifaces)
491

    
492
# This interface has no cp zone configured
493
add 1100 allow all from any to any
494

    
495
# block everything else
496
add 65534 deny all from any to any
497
EOD;
498

    
499
	/* load rules */
500
	file_put_contents("{$g['tmp_path']}/ipfw.cp.rules", $cprules);
501
	mwexec("/sbin/ipfw -q {$g['tmp_path']}/ipfw.cp.rules", true);
502
	@unlink("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules");
503
	unset($cprules);
504
}
505

    
506
/* Create a string with ipfw rule and increase rulenum */
507
function captiveportal_create_ipfw_rule($cmd, &$rulenum, $args) {
508
	$rule = "{$cmd} {$rulenum} {$args}\n";
509
	$rulenum++;
510

    
511
	return $rule;
512
}
513

    
514
/* Return first rule number for a cp zone */
515
function captiveportal_ipfw_ruleno($id) {
516
	global $g;
517

    
518
	return 2000 + $id * $g['captiveportal_rules_interval'];
519
}
520

    
521
/* reinit will disconnect all users, be careful! */
522
function captiveportal_init_rules($reinit = false) {
523
	global $config, $g, $cpzone, $cpzoneid;
524

    
525
	if (!isset($config['captiveportal'][$cpzone]['enable'])) {
526
		return;
527
	}
528

    
529
	captiveportal_load_modules();
530
	captiveportal_init_general_rules();
531

    
532
	/* Cleanup so nothing is leaked */
533
	captiveportal_free_dnrules();
534
	unlink_if_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules");
535

    
536
	$skipto = captiveportal_ipfw_ruleno($cpzoneid);
537

    
538
	$cprules = '';
539

    
540
	$cpips = array();
541
	$ifaces = get_configured_interface_list();
542
	$cpinterfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
543
	$firsttime = 0;
544
	foreach ($cpinterfaces as $cpifgrp) {
545
		if (!isset($ifaces[$cpifgrp])) {
546
			continue;
547
		}
548
		$tmpif = get_real_interface($cpifgrp);
549
		if (empty($tmpif)) {
550
			continue;
551
		}
552

    
553
		$cpipm = get_interface_ip($cpifgrp);
554

    
555
		if (!is_ipaddr($cpipm)) {
556
			continue;
557
		}
558

    
559
		$cpips[] = $cpipm;
560
		if (is_array($config['virtualip']['vip'])) {
561
			foreach ($config['virtualip']['vip'] as $vip) {
562
				if (($vip['interface'] == $cpifgrp) &&
563
				    (($vip['mode'] == "carp") ||
564
				    ($vip['mode'] == "ipalias"))) {
565
					$cpips[] = $vip['subnet'];
566
				}
567
			}
568
		}
569

    
570
		$cprules .= "table cp_ifaces add {$tmpif} {$skipto}\n";
571
	}
572
	if (count($cpips) > 0) {
573
		$cpactive = true;
574
	} else {
575
		return false;
576
	}
577

    
578
	if ($reinit == false) {
579
		$captiveportallck = lock("captiveportal{$cpzone}");
580
	}
581

    
582
	$rulenum = $skipto;
583
	$cprules .= "table {$cpzone}_pipe_mac create type mac valtype pipe\n";
584
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
585
	    "pipe tablearg MAC table({$cpzone}_pipe_mac)");
586
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
587
	    "allow pfsync from any to any");
588
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
589
	    "allow carp from any to any\n");
590
	$cprules .= "# layer 2: pass ARP\n";
591
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
592
	    "pass layer2 mac-type arp,rarp");
593
	$cprules .= "# pfsense requires for WPA\n";
594
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
595
	    "pass layer2 mac-type 0x888e,0x88c7");
596
	$cprules .= "# PPP Over Ethernet Session Stage/Discovery Stage\n";
597
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
598
	    "pass layer2 mac-type 0x8863,0x8864\n");
599
	$cprules .= "# layer 2: block anything else non-IP(v4/v6)\n";
600
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
601
	    "deny layer2 not mac-type ip,ipv6");
602

    
603
	/* These tables contain host ips */
604
	$cprules .= "table {$cpzone}_host_ips create type addr\n";
605
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
606
	    "pass ip from any to table({$cpzone}_host_ips) in");
607
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
608
	    "pass ip from table({$cpzone}_host_ips) to any out");
609
	foreach ($cpips as $cpip) {
610
		$cprules .= "table {$cpzone}_host_ips add {$cpip}\n";
611
	}
612
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
613
	    "pass ip from any to 255.255.255.255 in");
614
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
615
	    "pass ip from 255.255.255.255 to any out");
616

    
617
	/* Allowed ips */
618
	$cprules .= "table {$cpzone}_allowed_up create type addr valtype pipe\n";
619
	$cprules .= "table {$cpzone}_allowed_down create type addr valtype pipe\n";
620
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
621
	    "pipe tablearg ip from table({$cpzone}_allowed_up) to any in");
622
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
623
	    "pipe tablearg ip from any to table({$cpzone}_allowed_down) in");
624
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
625
	    "pipe tablearg ip from table({$cpzone}_allowed_up) to any out");
626
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
627
	    "pipe tablearg ip from any to table({$cpzone}_allowed_down) out");
628

    
629
	/* Authenticated users rules. */
630
	$cprules .= "table {$cpzone}_auth_up create type addr valtype pipe\n";
631
	$cprules .= "table {$cpzone}_auth_down create type addr valtype pipe\n";
632
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
633
	    "pipe tablearg ip from table({$cpzone}_auth_up) to any layer2 in");
634
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
635
	    "pipe tablearg ip from any to table({$cpzone}_auth_down) layer2 out");
636

    
637
	if (!empty($config['captiveportal'][$cpzone]['listenporthttp'])) {
638
		$listenporthttp = $config['captiveportal'][$cpzone]['listenporthttp'];
639
	} else {
640
		$listenporthttp = 8000 + $cpzoneid;
641
	}
642

    
643
	if (isset($config['captiveportal'][$cpzone]['httpslogin'])) {
644
		if (!empty($config['captiveportal'][$cpzone]['listenporthttps'])) {
645
			$listenporthttps = $config['captiveportal'][$cpzone]['listenporthttps'];
646
		} else {
647
			$listenporthttps = 8001 + $cpzoneid;
648
		}
649
		if (!isset($config['captiveportal'][$cpzone]['nohttpsforwards'])) {
650
			$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
651
			    "fwd 127.0.0.1,{$listenporthttps} tcp from any to any dst-port 443 in");
652
		}
653
	}
654

    
655
	$cprules .= "# redirect non-authenticated clients to captive portal\n";
656
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
657
	    "fwd 127.0.0.1,{$listenporthttp} tcp from any to any dst-port 80 in");
658
	$cprules .= "# let the responses from the captive portal web server back out\n";
659
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
660
	    "pass tcp from any to any out");
661
	$cprules .= "# This CP zone is over, skip to last rule\n";
662
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
663
	    "skipto 65534 all from any to any");
664

    
665
	/* generate passthru mac database */
666
	$cprules .= captiveportal_passthrumac_configure(true);
667
	$cprules .= "\n";
668

    
669
	/* allowed ipfw rules to make allowed ip work */
670
	$cprules .= captiveportal_allowedip_configure();
671

    
672
	/* allowed ipfw rules to make allowed hostnames work */
673
	$cprules .= captiveportal_allowedhostname_configure();
674

    
675
	/* load rules */
676
	captiveportal_delete_rules();
677
	file_put_contents("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules", $cprules);
678
	mwexec("/sbin/ipfw -q {$g['tmp_path']}/ipfw_{$cpzone}.cp.rules", true);
679
	@unlink("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules");
680
	unset($cprules);
681

    
682
	captiveportal_filterdns_configure();
683

    
684
	if ($reinit == false) {
685
		unlock($captiveportallck);
686
	}
687
}
688

    
689
/* Delete all rules related to specific cpzone */
690
function captiveportal_delete_rules($pipes_to_remove = array()) {
691
	global $g, $cpzoneid, $cpzone;
692

    
693
	$skipto1 = captiveportal_ipfw_ruleno($cpzoneid);
694
	$skipto2 = $skipto1 + $g['captiveportal_rules_interval'];
695

    
696
	$cp_ifaces = pfSense_ipfw_table_list("cp_ifaces");
697
	if (is_array($cp_ifaces)) {
698
		foreach ($cp_ifaces as $cp_iface) {
699
			if (empty($cp_iface['skipto']) ||
700
			    $cp_iface['skipto'] != $skipto1) {
701
				continue;
702
			}
703

    
704
			pfSense_ipfw_table("cp_ifaces", IP_FW_TABLE_XDEL,
705
			    $cp_iface['iface']);
706
		}
707
	}
708

    
709
	mwexec("/sbin/ipfw delete {$skipto1}-{$skipto2}", true);
710

    
711
	$tables = captiveportal_get_ipfw_table_names();
712

    
713
	$delrules = "";
714
	foreach ($tables as $table) {
715
		$delrules .= "table {$table} destroy\n";
716
	}
717

    
718
	foreach ($pipes_to_remove as $pipeno) {
719
		$delrules .= "pipe delete {$pipeno}\n";
720
	}
721

    
722
	if (empty($delrules)) {
723
		return;
724
	}
725

    
726
	file_put_contents("{$g['tmp_path']}/ipfw_{$cpzone}.deltable.rules", $delrules);
727
	mwexec("/sbin/ipfw -q {$g['tmp_path']}/ipfw_{$cpzone}.deltable.rules", true);
728
	@unlink("{$g['tmp_path']}/ipfw_{$cpzone}.deltable.rules");
729
}
730

    
731
/*
732
 * Remove clients that have been around for longer than the specified amount of time
733
 * db file structure:
734
 * timestamp,ipfw_rule_no,clientip,clientmac,username,sessionid,password,session_timeout,idle_timeout,session_terminate_time,interim_interval,traffic_quota,radiusctx
735
 * (password is in Base64 and only saved when reauthentication is enabled)
736
 */
737
function captiveportal_prune_old() {
738
	global $g, $config, $cpzone, $cpzoneid;
739

    
740
	if (empty($cpzone)) {
741
		return;
742
	}
743

    
744
	$cpcfg = $config['captiveportal'][$cpzone];
745
	$vcpcfg = $config['voucher'][$cpzone];
746

    
747
	/* check for expired entries */
748
	$idletimeout = 0;
749
	$timeout = 0;
750
	if (!empty($cpcfg['timeout']) && is_numeric($cpcfg['timeout'])) {
751
		$timeout = $cpcfg['timeout'] * 60;
752
	}
753

    
754
	if (!empty($cpcfg['idletimeout']) && is_numeric($cpcfg['idletimeout'])) {
755
		$idletimeout = $cpcfg['idletimeout'] * 60;
756
	}
757

    
758
	/* check for entries exceeding their traffic quota */
759
	$trafficquota = 0;
760
	if (!empty($cpcfg['trafficquota']) && is_numeric($cpcfg['trafficquota'])) {
761
		$trafficquota = $cpcfg['trafficquota'] * 1048576;
762
	}
763

    
764
	/* Is there any job to do? */
765
	if (!$timeout && !$idletimeout && !$trafficquota && !isset($cpcfg['reauthenticate']) &&
766
	    !isset($cpcfg['radiussession_timeout']) && !isset($cpcfg['radiustraffic_quota']) &&
767
	    !isset($vcpcfg['enable'])) {
768
		return;
769
	}
770

    
771
	$radiussrvs = captiveportal_get_radius_servers();
772

    
773
	/* Read database */
774
	/* NOTE: while this can be simplified in non radius case keep as is for now */
775
	$cpdb = captiveportal_read_db();
776

    
777
	$unsetindexes = array();
778
	$voucher_needs_sync = false;
779
	/*
780
	 * Snapshot the time here to use for calculation to speed up the process.
781
	 * If something is missed next run will catch it!
782
	 */
783
	$pruning_time = time();
784
	foreach ($cpdb as $cpentry) {
785
		$stop_time = $pruning_time;
786

    
787
		$timedout = false;
788
		$term_cause = 1;
789
		$logout_cause = 'TIMEOUT';
790
		if (empty($cpentry[12])) {
791
			$cpentry[12] = 'first';
792
		}
793
		$radiusservers = $radiussrvs[$cpentry[12]];
794

    
795
		/* hard timeout or session_timeout from radius if enabled */
796
		if (isset($cpcfg['radiussession_timeout'])) {
797
			$timeout = (is_numeric($cpentry[7])) ? $cpentry[7] : $timeout;
798
		}
799
		if ($timeout) {
800
			if (($pruning_time - $cpentry[0]) >= $timeout) {
801
				$timedout = true;
802
				$term_cause = 5; // Session-Timeout
803
				$logout_cause = 'SESSION TIMEOUT';
804
			}
805
		}
806

    
807
		/* Session-Terminate-Time */
808
		if (!$timedout && !empty($cpentry[9])) {
809
			if ($pruning_time >= $cpentry[9]) {
810
				$timedout = true;
811
				$term_cause = 5; // Session-Timeout
812
				$logout_cause = 'SESSION TIMEOUT';
813
			}
814
		}
815

    
816
		/* check if the radius idle_timeout attribute has been set and if its set change the idletimeout to this value */
817
		$uidletimeout = (is_numeric($cpentry[8])) ? $cpentry[8] : $idletimeout;
818
		/* if an idle timeout is specified, get last activity timestamp from ipfw */
819
		if (!$timedout && $uidletimeout > 0) {
820
			$lastact = captiveportal_get_last_activity($cpentry[2]);
821
			/*	If the user has logged on but not sent any traffic they will never be logged out.
822
			 *	We "fix" this by setting lastact to the login timestamp.
823
			 */
824
			$lastact = $lastact ? $lastact : $cpentry[0];
825
			if ($lastact && (($pruning_time - $lastact) >= $uidletimeout)) {
826
				$timedout = true;
827
				$term_cause = 4; // Idle-Timeout
828
				$logout_cause = 'IDLE TIMEOUT';
829
				if (!isset($config['captiveportal'][$cpzone]['includeidletime'])) {
830
					$stop_time = $lastact;
831
				}
832
			}
833
		}
834

    
835
		/* if vouchers are configured, activate session timeouts */
836
		if (!$timedout && isset($vcpcfg['enable']) && !empty($cpentry[7])) {
837
			if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
838
				$timedout = true;
839
				$term_cause = 5; // Session-Timeout
840
				$logout_cause = 'SESSION TIMEOUT';
841
				$voucher_needs_sync = true;
842
			}
843
		}
844

    
845
		/* traffic quota, value retrieved from the radius attribute if the option is enabled */
846
		if (isset($cpcfg['radiustraffic_quota'])) {
847
			$trafficquota = (is_numeric($cpentry[11])) ? $cpentry[11] : $trafficquota;
848
		}
849
		if (!$timedout && $trafficquota > 0) {
850
			$volume = getVolume($cpentry[2], $cpentry[3]);
851
			if (($volume['input_bytes'] + $volume['output_bytes']) > $trafficquota) {
852
				$timedout = true;
853
				$term_cause = 10; // NAS-Request
854
				$logout_cause = 'QUOTA EXCEEDED';
855
			}
856
		}
857

    
858
		if ($timedout) {
859
			captiveportal_disconnect($cpentry, $radiusservers, $term_cause, $stop_time);
860
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], $logout_cause);
861
			$unsetindexes[] = $cpentry[5];
862
		}
863

    
864
		/* do periodic RADIUS reauthentication? */
865
		if (!$timedout && !empty($radiusservers)) {
866
			if (isset($cpcfg['radacct_enable'])) {
867
				if (substr($cpcfg['reauthenticateacct'], 0, 9) == "stopstart") {
868
					/* stop and restart accounting */
869
					if ($cpcfg['reauthenticateacct'] == "stopstartfreeradius") {
870
						$rastart_time = 0;
871
						$rastop_time = 60;
872
					} else {
873
						$rastart_time = $cpentry[0];
874
						$rastop_time = null;
875
					}
876
					RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
877
						$cpentry[4], // username
878
						$cpentry[5], // sessionid
879
						$rastart_time, // start time
880
						$radiusservers,
881
						$cpentry[2], // clientip
882
						$cpentry[3], // clientmac
883
						10, // NAS Request
884
						false, // Not an interim request
885
						$rastop_time); // Stop Time
886
					$clientsn = (is_ipaddrv6($cpentry[2])) ? 128 : 32;
887
					pfSense_ipfw_table_zerocnt("{$cpzone}_auth_up", "{$cpentry[2]}/{$clientsn}");
888
					pfSense_ipfw_table_zerocnt("{$cpzone}_auth_down", "{$cpentry[2]}/{$clientsn}");
889
					if ($cpcfg['reauthenticateacct'] == "stopstartfreeradius") {
890
						/* Need to pause here or the FreeRADIUS server gets confused about packet ordering. */
891
						sleep(1);
892
					}
893
					RADIUS_ACCOUNTING_START($cpentry[1], // ruleno
894
						$cpentry[4], // username
895
						$cpentry[5], // sessionid
896
						$radiusservers,
897
						$cpentry[2], // clientip
898
						$cpentry[3]); // clientmac
899
				} else if ($cpcfg['reauthenticateacct'] == "interimupdate") {
900
					$session_time = $pruning_time - $cpentry[0];
901
					if (!empty($cpentry[10]) && $cpentry[10] > 60) {
902
						$interval = $cpentry[10];
903
					} else {
904
						$interval = 0;
905
					}
906
					$past_interval_min = ($session_time > $interval);
907
					if ($interval != 0) {
908
						$within_interval = ($session_time % $interval >= 0 && $session_time % $interval <= 59);
909
					}
910
					if ($interval === 0 || ($interval > 0 && $past_interval_min && $within_interval)) {
911
						RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
912
							$cpentry[4], // username
913
							$cpentry[5], // sessionid
914
							$cpentry[0], // start time
915
							$radiusservers,
916
							$cpentry[2], // clientip
917
							$cpentry[3], // clientmac
918
							10, // NAS Request
919
							true); // Interim Updates
920
					}
921
				}
922
			}
923

    
924
			/* check this user against RADIUS again */
925
			if (isset($cpcfg['reauthenticate'])) {
926
				$auth_list = RADIUS_AUTHENTICATION($cpentry[4], // username
927
					base64_decode($cpentry[6]), // password
928
					$radiusservers,
929
					$cpentry[2], // clientip
930
					$cpentry[3], // clientmac
931
					$cpentry[1]); // ruleno
932
				if ($auth_list['auth_val'] == 3) {
933
					captiveportal_disconnect($cpentry, $radiusservers, 17);
934
					captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "RADIUS_DISCONNECT", $auth_list['reply_message']);
935
					$unsetindexes[] = $cpentry[5];
936
				} else if ($auth_list['auth_val'] == 2) {
937
					captiveportal_reapply_attributes($cpentry, $auth_list);
938
				}
939
			}
940
		}
941
	}
942
	unset($cpdb);
943

    
944
	captiveportal_prune_old_automac();
945

    
946
	if ($voucher_needs_sync == true) {
947
		/* Trigger a sync of the vouchers on config */
948
		send_event("service sync vouchers");
949
	}
950

    
951
	/* write database */
952
	if (!empty($unsetindexes)) {
953
		captiveportal_remove_entries($unsetindexes);
954
	}
955
}
956

    
957
function captiveportal_prune_old_automac() {
958
	global $g, $config, $cpzone, $cpzoneid;
959

    
960
	if (is_array($config['captiveportal'][$cpzone]['passthrumac']) &&
961
	    isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
962
		$tmpvoucherdb = array();
963
		$macrules = "";
964
		$writecfg = false;
965
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $eid => $emac) {
966
			if ($emac['logintype'] != "voucher") {
967
				continue;
968
			}
969
			if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
970
				if (isset($tmpvoucherdb[$emac['username']])) {
971
					$temac = $config['captiveportal'][$cpzone]['passthrumac'][$tmpvoucherdb[$emac['username']]];
972
					$pipeno = captiveportal_get_dn_passthru_ruleno($temac['mac']);
973
					if ($pipeno) {
974
						captiveportal_free_dn_ruleno($pipeno);
975
						$macrules .= "table {$cpzone}_pipe_mac delete any,{$temac['mac']}\n";
976
						$macrules .= "table {$cpzone}_pipe_mac delete {$temac['mac']},any\n";
977
						$macrules .= "pipe delete {$pipeno}\n";
978
						++$pipeno;
979
						$macrules .= "pipe delete {$pipeno}\n";
980
					}
981
					$writecfg = true;
982
					captiveportal_logportalauth($temac['username'], $temac['mac'],
983
					    $temac['ip'], "DUPLICATE {$temac['username']} LOGIN - TERMINATING OLD SESSION");
984
					unset($config['captiveportal'][$cpzone]['passthrumac'][$tmpvoucherdb[$emac['username']]]);
985
				}
986
				$tmpvoucherdb[$emac['username']] = $eid;
987
			}
988
			if (voucher_auth($emac['username']) <= 0) {
989
				$pipeno = captiveportal_get_dn_passthru_ruleno($emac['mac']);
990
				if ($pipeno) {
991
					captiveportal_free_dn_ruleno($pipeno);
992
					$macrules .= "table {$cpzone}_pipe_mac delete any,{$emac['mac']}\n";
993
					$macrules .= "table {$cpzone}_pipe_mac delete {$emac['mac']},any\n";
994
					$macrules .= "pipe delete {$pipeno}\n";
995
					++$pipeno;
996
					$macrules .= "pipe delete {$pipeno}\n";
997
				}
998
				$writecfg = true;
999
				captiveportal_logportalauth($emac['username'], $emac['mac'],
1000
				    $emac['ip'], "EXPIRED {$emac['username']} LOGIN - TERMINATING SESSION");
1001
				unset($config['captiveportal'][$cpzone]['passthrumac'][$eid]);
1002
			}
1003
		}
1004
		unset($tmpvoucherdb);
1005
		if (!empty($macrules)) {
1006
			@file_put_contents("{$g['tmp_path']}/macentry.prunerules.tmp", $macrules);
1007
			unset($macrules);
1008
			mwexec("/sbin/ipfw -q {$g['tmp_path']}/macentry.prunerules.tmp");
1009
		}
1010
		if ($writecfg === true) {
1011
			write_config("Prune session for auto-added macs");
1012
		}
1013
	}
1014
}
1015

    
1016
/* remove a single client according to the DB entry */
1017
function captiveportal_disconnect($dbent, $radiusservers, $term_cause = 1,
1018
    $stop_time = null) {
1019
	global $g, $config, $cpzone, $cpzoneid;
1020

    
1021
	$stop_time = (empty($stop_time)) ? time() : $stop_time;
1022

    
1023
	/* this client needs to be deleted - remove ipfw rules */
1024
	if (isset($config['captiveportal'][$cpzone]['radacct_enable']) &&
1025
	    !empty($radiusservers)) {
1026
		if ($config['captiveportal'][$cpzone]['reauthenticateacct'] ==
1027
		    "stopstartfreeradius") {
1028
			/*
1029
			 * Interim updates are on so the session time must be
1030
			 * reported as the elapsed time since the previous
1031
			 * interim update.
1032
			 */
1033
			$session_time = ($stop_time - $dbent[0]) % 60;
1034
			$start_time = $stop_time - $session_time;
1035
		} else {
1036
			$start_time = $dbent[0];
1037
		}
1038
		RADIUS_ACCOUNTING_STOP($dbent[1], // ruleno
1039
			$dbent[4], // username
1040
			$dbent[5], // sessionid
1041
			$start_time, // start time
1042
			$radiusservers,
1043
			$dbent[2], // clientip
1044
			$dbent[3], // clientmac
1045
			$term_cause, // Acct-Terminate-Cause
1046
			false,
1047
			$stop_time);
1048
	}
1049

    
1050
	if (is_ipaddr($dbent[2])) {
1051
		/*
1052
		 * Delete client's ip entry from tables auth_up and auth_down.
1053
		 * It's not necessary to explicit specify mac address here
1054
		 */
1055
		$cpsession = captiveportal_isip_logged($dbent[2]);
1056
		if (!empty($cpsession)) {
1057
			$clientsn = (is_ipaddrv6($dbent[2])) ? 128 : 32;
1058
			pfSense_ipfw_table("{$cpzone}_auth_up",
1059
			    IP_FW_TABLE_XDEL, "{$dbent[2]}/{$clientsn}");
1060
			pfSense_ipfw_table("{$cpzone}_auth_down",
1061
			    IP_FW_TABLE_XDEL, "{$dbent[2]}/{$clientsn}");
1062
		}
1063
		/* XXX: Redundant?! Ensure all pf(4) states are killed. */
1064
		$_gb = @pfSense_kill_states($dbent[2]);
1065
		$_gb = @pfSense_kill_srcstates($dbent[2]);
1066
	}
1067

    
1068
	/*
1069
	 * These are the pipe numbers we use to control traffic shaping for
1070
	 * each logged in user via captive portal
1071
	 * We could get an error if the pipe doesn't exist but everything
1072
	 * should still be fine
1073
	 */
1074
	if (!empty($dbent[1])) {
1075
		/*
1076
		 * Call captiveportal_free_dnrules() in dry_run mode to verify
1077
		 * if there are pipes to be removed and prevent the attempt to
1078
		 * delete invalid pipes
1079
		 */
1080
		$removed_pipes = captiveportal_free_dnrules($dbent[1],
1081
		    $dbent[1]+1, true);
1082

    
1083
		if (!empty($removed_pipes)) {
1084
			$_gb = @pfSense_ipfw_pipe("pipe delete {$dbent[1]}");
1085
			$_gb = @pfSense_ipfw_pipe("pipe delete " .
1086
			    ($dbent[1]+1));
1087

    
1088
			/*
1089
			 * Release the ruleno so it can be reallocated to new
1090
			 * clients
1091
			 */
1092
			captiveportal_free_dn_ruleno($dbent[1]);
1093
		}
1094
	}
1095

    
1096
	// XMLRPC Call over to the master Voucher node
1097
	if (xmlrpc_sync_voucher_details($syncip, $syncport,
1098
	    $vouchersyncusername, $syncpass)) {
1099
		$remote_status = xmlrpc_sync_voucher_disconnect($dbent, $syncip,
1100
		    $syncport, $syncpass, $vouchersyncusername, $term_cause,
1101
		    $stop_time);
1102
	}
1103

    
1104
}
1105

    
1106
/* remove a single client by sessionid */
1107
function captiveportal_disconnect_client($sessionid, $term_cause = 1, $logoutReason = "LOGOUT") {
1108
	global $g, $config;
1109

    
1110
	$sessionid = SQLite3::escapeString($sessionid);
1111
	$radiusservers = captiveportal_get_radius_servers();
1112

    
1113
	/* read database */
1114
	$result = captiveportal_read_db("WHERE sessionid = '{$sessionid}'");
1115

    
1116
	/* find entry */
1117
	if (!empty($result)) {
1118
		captiveportal_write_db("DELETE FROM captiveportal WHERE sessionid = '{$sessionid}'");
1119

    
1120
		foreach ($result as $cpentry) {
1121
			if (empty($cpentry[12])) {
1122
				$cpentry[12] = 'first';
1123
			}
1124
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[12]], $term_cause);
1125
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "DISCONNECT");
1126
		}
1127
		unset($result);
1128
	}
1129
}
1130

    
1131
/* remove all clients */
1132
function captiveportal_disconnect_all($term_cause = 6, $logoutReason = "DISCONNECT") {
1133
	global $g, $config, $cpzone, $cpzoneid;
1134

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

    
1138
	/* if we still don't have the lock, unlock forcefully and take it */
1139
	if (!$rcprunelock) {
1140
		log_error("CP zone ${cpzone}: could not obtain the lock for more than 15 seconds, lock taken forcefully to disconnect all users");
1141
		unlock_force("rcprunecaptiveportal{$cpzone}");
1142
		$rcprunelock = lock("rcprunecaptiveportal{$cpzone}", LOCK_EX);
1143
	}
1144

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

    
1148
	captiveportal_radius_stop_all($term_cause, $logoutReason);
1149

    
1150
	/* remove users from the database */
1151
	$cpdb = captiveportal_read_db();
1152
	$unsetindexes = array_column($cpdb,5);
1153
	if (!empty($unsetindexes)) {
1154
		captiveportal_remove_entries($unsetindexes);
1155
	}
1156

    
1157
	/* reinit ipfw rules */
1158
	captiveportal_init_rules(true);
1159

    
1160
	unlock($cpdblck);
1161
	unlock($rcprunelock);
1162
}
1163

    
1164
/* send RADIUS acct stop for all current clients */
1165
function captiveportal_radius_stop_all($term_cause = 6, $logoutReason = "DISCONNECT") {
1166
	global $g, $config, $cpzone, $cpzoneid;
1167

    
1168
	$cpdb = captiveportal_read_db();
1169

    
1170
	$radacct = isset($config['captiveportal'][$cpzone]['radacct_enable']) ? true : false;
1171
	if ($radacct) {
1172
		$radiusservers = captiveportal_get_radius_servers();
1173
	}
1174

    
1175
	foreach ($cpdb as $cpentry) {
1176
		if ($radacct) {
1177
			if (!empty($radiusservers)) {
1178
				if (empty($cpentry[12])) {
1179
					$cpentry[12] = 'first';
1180
				}
1181
				if (!empty($radiusservers[$cpentry[12]])) {
1182
					RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
1183
						$cpentry[4], // username
1184
						$cpentry[5], // sessionid
1185
						$cpentry[0], // start time
1186
						$radiusservers[$cpentry[12]],
1187
						$cpentry[2], // clientip
1188
						$cpentry[3], // clientmac
1189
						$term_cause);
1190
				}
1191
			}
1192
		}
1193
		captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], $logoutReason);
1194
	}
1195
	unset($cpdb);
1196
}
1197

    
1198
function captiveportal_passthrumac_configure_entry($macent, $pipeinrule = false) {
1199
	global $config, $g, $cpzone;
1200

    
1201
	$bwUp = 0;
1202
	if (!empty($macent['bw_up'])) {
1203
		$bwUp = $macent['bw_up'];
1204
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1205
		$bwUp = $config['captiveportal'][$cpzone]['bwdefaultup'];
1206
	}
1207
	$bwDown = 0;
1208
	if (!empty($macent['bw_down'])) {
1209
		$bwDown = $macent['bw_down'];
1210
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1211
		$bwDown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1212
	}
1213

    
1214
	if ($macent['action'] == 'pass') {
1215
		$rules = "";
1216

    
1217
		$pipeno = captiveportal_get_next_dn_ruleno();
1218

    
1219
		$pipeup = $pipeno;
1220
		if ($pipeinrule == true) {
1221
			$_gb = @pfSense_ipfw_pipe("pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16");
1222
		} else {
1223
			$rules .= "pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16\n";
1224
		}
1225

    
1226
		$pipedown = $pipeno + 1;
1227
		if ($pipeinrule == true) {
1228
			$_gb = @pfSense_ipfw_pipe("pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16");
1229
		} else {
1230
			$rules .= "pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16\n";
1231
		}
1232

    
1233
		$rules .= "table {$cpzone}_pipe_mac add any,{$macent['mac']} {$pipeup}\n";
1234
		$rules .= "table {$cpzone}_pipe_mac add {$macent['mac']},any {$pipedown}\n";
1235
	}
1236

    
1237
	return $rules;
1238
}
1239

    
1240
function captiveportal_passthrumac_delete_entry($macent) {
1241
	global $cpzone;
1242
	$rules = "";
1243

    
1244
	if ($macent['action'] == 'pass') {
1245
		$pipeno = captiveportal_get_dn_passthru_ruleno($macent['mac']);
1246

    
1247
		if (!empty($pipeno)) {
1248
			captiveportal_free_dn_ruleno($pipeno);
1249
			$rules .= "table {$cpzone}_pipe_mac delete any,{$macent['mac']}\n";
1250
			$rules .= "table {$cpzone}_pipe_mac delete {$macent['mac']},any\n";
1251
			$rules .= "pipe delete " . $pipeno . "\n";
1252
			$rules .= "pipe delete " . ++$pipeno . "\n";
1253
		}
1254
	}
1255

    
1256
	return $rules;
1257
}
1258

    
1259
function captiveportal_passthrumac_configure($filename = false, $startindex = 0, $stopindex = 0) {
1260
	global $config, $g, $cpzone;
1261

    
1262
	$rules = "";
1263

    
1264
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1265
		if ($stopindex > 0) {
1266
			$fd = fopen($filename, "w");
1267
			for ($idx = $startindex; $idx <= $stopindex; $idx++) {
1268
				if (isset($config['captiveportal'][$cpzone]['passthrumac'][$idx])) {
1269
					$rules = captiveportal_passthrumac_configure_entry($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
1270
					fwrite($fd, $rules);
1271
				}
1272
			}
1273
			fclose($fd);
1274

    
1275
			return;
1276
		} else {
1277
			$nentries = count($config['captiveportal'][$cpzone]['passthrumac']);
1278
			if ($nentries > 2000) {
1279
				$nloops = $nentries / 1000;
1280
				$remainder= $nentries % 1000;
1281
				for ($i = 0; $i < $nloops; $i++) {
1282
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . ((($i+1) * 1000) - 1) . "\"");
1283
				}
1284
				if ($remainder > 0) {
1285
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . (($i* 1000) + $remainder) ."\"");
1286
				}
1287
			} else {
1288
				foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1289
					$rules .= captiveportal_passthrumac_configure_entry($macent, true);
1290
				}
1291
			}
1292
		}
1293
	}
1294

    
1295
	return $rules;
1296
}
1297

    
1298
function captiveportal_passthrumac_findbyname($username) {
1299
	global $config, $cpzone;
1300

    
1301
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1302
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1303
			if ($macent['username'] == $username) {
1304
				return $macent;
1305
			}
1306
		}
1307
	}
1308
	return NULL;
1309
}
1310

    
1311
/*
1312
 * table (3=IN)/(4=OUT) hold allowed ip's without bw limits
1313
 */
1314
function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) {
1315
	global $g, $config, $cpzone;
1316

    
1317
	/*  Instead of copying this entire function for something
1318
	 *  easy such as hostname vs ip address add this check
1319
	 */
1320
	if ($ishostname === true) {
1321
		if (!platform_booting()) {
1322
			$ipaddress = gethostbyname($ipent['hostname']);
1323
			if (!is_ipaddr($ipaddress)) {
1324
				return;
1325
			}
1326
		} else {
1327
			$ipaddress = "";
1328
		}
1329
	} else {
1330
		$ipaddress = $ipent['ip'];
1331
	}
1332

    
1333
	$rules = "";
1334
	$cp_filterdns_conf = "";
1335
	$enBwup = 0;
1336
	if (!empty($ipent['bw_up'])) {
1337
		$enBwup = intval($ipent['bw_up']);
1338
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1339
		$enBwup = $config['captiveportal'][$cpzone]['bwdefaultup'];
1340
	}
1341
	$enBwdown = 0;
1342
	if (!empty($ipent['bw_down'])) {
1343
		$enBwdown = intval($ipent['bw_down']);
1344
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1345
		$enBwdown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1346
	}
1347

    
1348
	$pipeup = captiveportal_get_next_dn_ruleno();
1349
	$_gb = @pfSense_ipfw_pipe("pipe {$pipeup} config bw {$enBwup}Kbit/s queue 100 buckets 16");
1350
	$pipedown = $pipeup + 1;
1351
	$_gb = @pfSense_ipfw_pipe("pipe {$pipedown} config bw {$enBwdown}Kbit/s queue 100 buckets 16");
1352

    
1353
	if ($ishostname === true) {
1354
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} {$cpzone}_allowed_up pipe {$pipeup}\n";
1355
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} {$cpzone}_allowed_down pipe {$pipedown}\n";
1356
		if (!is_ipaddr($ipaddress)) {
1357
			return array("", $cp_filterdns_conf);
1358
		}
1359
	}
1360

    
1361
	$subnet = "";
1362
	if (!empty($ipent['sn'])) {
1363
		$subnet = "/{$ipent['sn']}";
1364
	}
1365
	$rules .= "table {$cpzone}_allowed_up add {$ipaddress}{$subnet} {$pipeup}\n";
1366
	$rules .= "table {$cpzone}_allowed_down add {$ipaddress}{$subnet} {$pipedown}\n";
1367

    
1368
	if ($ishostname === true) {
1369
		return array($rules, $cp_filterdns_conf);
1370
	} else {
1371
		return $rules;
1372
	}
1373
}
1374

    
1375
function captiveportal_allowedhostname_configure() {
1376
	global $config, $g, $cpzone, $cpzoneid;
1377

    
1378
	$rules = "";
1379
	if (!is_array($config['captiveportal'][$cpzone]['allowedhostname'])) {
1380
		return $rules;
1381
	}
1382

    
1383
	$rules = "\n# captiveportal_allowedhostname_configure()\n";
1384
	$cp_filterdns_conf = "";
1385
	foreach ($config['captiveportal'][$cpzone]['allowedhostname'] as $hostnameent) {
1386
		$tmprules = captiveportal_allowedip_configure_entry($hostnameent, true);
1387
		$rules .= $tmprules[0];
1388
		$cp_filterdns_conf .= $tmprules[1];
1389
	}
1390
	$cp_filterdns_filename = "{$g['varetc_path']}/filterdns-{$cpzone}-captiveportal.conf";
1391
	@file_put_contents($cp_filterdns_filename, $cp_filterdns_conf);
1392
	unset($cp_filterdns_conf);
1393

    
1394
	return $rules;
1395
}
1396

    
1397
function captiveportal_filterdns_configure() {
1398
	global $config, $g, $cpzone, $cpzoneid;
1399

    
1400
	$cp_filterdns_filename = $g['varetc_path'] .
1401
	    "/filterdns-{$cpzone}-captiveportal.conf";
1402

    
1403
	if (isset($config['captiveportal'][$cpzone]['enable']) &&
1404
	    is_array($config['captiveportal'][$cpzone]['allowedhostname']) &&
1405
	    file_exists($cp_filterdns_filename)) {
1406
		if (isvalidpid($g['varrun_path'] .
1407
		    "/filterdns-{$cpzone}-cpah.pid")) {
1408
			sigkillbypid($g['varrun_path'] .
1409
			    "/filterdns-{$cpzone}-cpah.pid", "HUP");
1410
		} else {
1411
			mwexec("/usr/local/sbin/filterdns -p " .
1412
			    "{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid" .
1413
			    " -i 300 -c {$cp_filterdns_filename} -d 1");
1414
		}
1415
	} else {
1416
		killbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1417
		@unlink("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1418
	}
1419

    
1420
	return $rules;
1421
}
1422

    
1423
function captiveportal_allowedip_configure() {
1424
	global $config, $g, $cpzone;
1425

    
1426
	$rules = "";
1427
	if (is_array($config['captiveportal'][$cpzone]['allowedip'])) {
1428
		foreach ($config['captiveportal'][$cpzone]['allowedip'] as $ipent) {
1429
			$rules .= captiveportal_allowedip_configure_entry($ipent);
1430
		}
1431
	}
1432

    
1433
	return $rules;
1434
}
1435

    
1436
/* get last activity timestamp given client IP address */
1437
function captiveportal_get_last_activity($ip) {
1438
	global $cpzone;
1439

    
1440
	/* Reading only from one of the tables is enough of approximation. */
1441
	$tables = array("{$cpzone}_allowed_up", "{$cpzone}_auth_up");
1442

    
1443
	foreach ($tables as $table) {
1444
		$ipfw = pfSense_ipfw_table_lookup($table, $ip);
1445
		if (is_array($ipfw)) {
1446
			/* Workaround for #46652 */
1447
			if ($ipfw['packets'] > 0) {
1448
				return $ipfw['timestamp'];
1449
			} else {
1450
				return 0;
1451
			}
1452
		}
1453
	}
1454

    
1455
	return 0;
1456
}
1457

    
1458
function captiveportal_init_radius_servers() {
1459
	global $config, $g, $cpzone;
1460

    
1461
	/* generate radius server database */
1462
	if ($config['captiveportal'][$cpzone]['radiusip'] &&
1463
	    (!isset($config['captiveportal'][$cpzone]['auth_method']) || $config['captiveportal'][$cpzone]['auth_method'] == "radius")) {
1464
		$radiusip = $config['captiveportal'][$cpzone]['radiusip'];
1465
		$radiusip2 = ($config['captiveportal'][$cpzone]['radiusip2']) ? $config['captiveportal'][$cpzone]['radiusip2'] : null;
1466
		$radiusip3 = ($config['captiveportal'][$cpzone]['radiusip3']) ? $config['captiveportal'][$cpzone]['radiusip3'] : null;
1467
		$radiusip4 = ($config['captiveportal'][$cpzone]['radiusip4']) ? $config['captiveportal'][$cpzone]['radiusip4'] : null;
1468

    
1469
		if ($config['captiveportal'][$cpzone]['radiusport']) {
1470
			$radiusport = $config['captiveportal'][$cpzone]['radiusport'];
1471
		} else {
1472
			$radiusport = 1812;
1473
		}
1474
		if ($config['captiveportal'][$cpzone]['radiusacctport']) {
1475
			$radiusacctport = $config['captiveportal'][$cpzone]['radiusacctport'];
1476
		} else {
1477
			$radiusacctport = 1813;
1478
		}
1479
		if ($config['captiveportal'][$cpzone]['radiusport2']) {
1480
			$radiusport2 = $config['captiveportal'][$cpzone]['radiusport2'];
1481
		} else {
1482
			$radiusport2 = 1812;
1483
		}
1484
		if ($config['captiveportal'][$cpzone]['radiusport3']) {
1485
			$radiusport3 = $config['captiveportal'][$cpzone]['radiusport3'];
1486
		} else {
1487
			$radiusport3 = 1812;
1488
		}
1489
		if ($config['captiveportal'][$cpzone]['radiusport4']) {
1490
			$radiusport4 = $config['captiveportal'][$cpzone]['radiusport4'];
1491
		} else {
1492
			$radiusport4 = 1812;
1493
		}
1494

    
1495
		$radiuskey = $config['captiveportal'][$cpzone]['radiuskey'];
1496
		$radiuskey2 = $config['captiveportal'][$cpzone]['radiuskey2'];
1497
		$radiuskey3 = $config['captiveportal'][$cpzone]['radiuskey3'];
1498
		$radiuskey4 = $config['captiveportal'][$cpzone]['radiuskey4'];
1499

    
1500
		$cprdsrvlck = lock("captiveportalradius{$cpzone}", LOCK_EX);
1501
		$fd = @fopen("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db", "w");
1502
		if (!$fd) {
1503
			captiveportal_syslog("Error: cannot open RADIUS DB file in captiveportal_configure().\n");
1504
			unlock($cprdsrvlck);
1505
			return 1;
1506
		}
1507
		if (isset($radiusip)) {
1508
			fwrite($fd, $radiusip . "," . $radiusport . "," . $radiusacctport . "," . $radiuskey . ",first");
1509
		}
1510
		if (isset($radiusip2)) {
1511
			fwrite($fd, "\n" . $radiusip2 . "," . $radiusport2 . "," . $radiusacctport . "," . $radiuskey2 . ",first");
1512
		}
1513
		if (isset($radiusip3)) {
1514
			fwrite($fd, "\n" . $radiusip3 . "," . $radiusport3 . "," . $radiusacctport . "," . $radiuskey3 . ",second");
1515
		}
1516
		if (isset($radiusip4)) {
1517
			fwrite($fd, "\n" . $radiusip4 . "," . $radiusport4 . "," . $radiusacctport . "," . $radiuskey4 . ",second");
1518
		}
1519

    
1520
		fclose($fd);
1521
		unlock($cprdsrvlck);
1522
	}
1523
}
1524

    
1525
/* read RADIUS servers into array */
1526
function captiveportal_get_radius_servers() {
1527
	global $g, $cpzone;
1528

    
1529
	$cprdsrvlck = lock("captiveportalradius{$cpzone}");
1530
	if (file_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db")) {
1531
		$radiusservers = array();
1532
		$cpradiusdb = file("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db",
1533
		FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1534
		if ($cpradiusdb) {
1535
			foreach ($cpradiusdb as $cpradiusentry) {
1536
				$line = trim($cpradiusentry);
1537
				if ($line) {
1538
					$radsrv = array();
1539
					list($radsrv['ipaddr'], $radsrv['port'], $radsrv['acctport'], $radsrv['key'], $context) = explode(",", $line);
1540
				}
1541
				if (empty($context)) {
1542
					if (!is_array($radiusservers['first'])) {
1543
						$radiusservers['first'] = array();
1544
					}
1545
					$radiusservers['first'] = $radsrv;
1546
				} else {
1547
					if (!is_array($radiusservers[$context])) {
1548
						$radiusservers[$context] = array();
1549
					}
1550
					$radiusservers[$context][] = $radsrv;
1551
				}
1552
			}
1553
		}
1554
		unlock($cprdsrvlck);
1555
		return $radiusservers;
1556
	}
1557

    
1558
	unlock($cprdsrvlck);
1559
	return false;
1560
}
1561

    
1562
/* log successful captive portal authentication to syslog */
1563
/* part of this code from php.net */
1564
function captiveportal_logportalauth($user, $mac, $ip, $status, $message = null) {
1565
	// Log it
1566
	if (!$message) {
1567
		$message = "{$status}: {$user}, {$mac}, {$ip}";
1568
	} else {
1569
		$message = trim($message);
1570
		$message = "{$status}: {$user}, {$mac}, {$ip}, {$message}";
1571
	}
1572
	captiveportal_syslog($message);
1573
}
1574

    
1575
/* log simple messages to syslog */
1576
function captiveportal_syslog($message) {
1577
	global $cpzone;
1578

    
1579
	$message = trim($message);
1580
	$message = "Zone: {$cpzone} - {$message}";
1581
	openlog("logportalauth", LOG_PID, LOG_LOCAL4);
1582
	// Log it
1583
	syslog(LOG_INFO, $message);
1584
	closelog();
1585
}
1586

    
1587
function radius($username, $password, $clientip, $clientmac, $type, $radiusctx = null) {
1588
	global $g, $config, $cpzoneid;
1589

    
1590
	$pipeno = captiveportal_get_next_dn_ruleno();
1591

    
1592
	/* If the pool is empty, return appropriate message and fail authentication */
1593
	if (empty($pipeno)) {
1594
		$auth_list = array();
1595
		$auth_list['auth_val'] = 1;
1596
		$auth_list['error'] = "System reached maximum login capacity";
1597
		return $auth_list;
1598
	}
1599

    
1600
	$radiusservers = captiveportal_get_radius_servers();
1601

    
1602
	if (is_null($radiusctx)) {
1603
		$radiusctx = 'first';
1604
	}
1605

    
1606
	$auth_list = RADIUS_AUTHENTICATION($username,
1607
		$password,
1608
		$radiusservers[$radiusctx],
1609
		$clientip,
1610
		$clientmac,
1611
		$pipeno);
1612

    
1613
	if ($auth_list['auth_val'] == 2) {
1614
		captiveportal_logportalauth($username, $clientmac, $clientip, $type);
1615
		$sessionid = portal_allow($clientip,
1616
			$clientmac,
1617
			$username,
1618
			$password,
1619
			$auth_list,
1620
			$pipeno,
1621
			$radiusctx);
1622
	} else {
1623
		captiveportal_free_dn_ruleno($pipeno);
1624
	}
1625

    
1626
	return $auth_list;
1627
}
1628

    
1629
function captiveportal_opendb() {
1630
	global $g, $config, $cpzone, $cpzoneid;
1631

    
1632
	$db_path = "{$g['vardb_path']}/captiveportal{$cpzone}.db";
1633
	$createquery = "CREATE TABLE IF NOT EXISTS captiveportal (" .
1634
				"allow_time INTEGER, pipeno INTEGER, ip TEXT, mac TEXT, username TEXT, " .
1635
				"sessionid TEXT, bpassword TEXT, session_timeout INTEGER, idle_timeout INTEGER, " .
1636
				"session_terminate_time INTEGER, interim_interval INTEGER, traffic_quota INTEGER, " .
1637
				"radiusctx TEXT); " .
1638
			"CREATE UNIQUE INDEX IF NOT EXISTS idx_active ON captiveportal (sessionid, username); " .
1639
			"CREATE INDEX IF NOT EXISTS user ON captiveportal (username); " .
1640
			"CREATE INDEX IF NOT EXISTS ip ON captiveportal (ip); " .
1641
			"CREATE INDEX IF NOT EXISTS starttime ON captiveportal (allow_time)";
1642

    
1643
	try {
1644
		$DB = new SQLite3($db_path);
1645
		$DB->busyTimeout(60000);
1646
	} catch (Exception $e) {
1647
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: " . $e->getMessage() . " -- Trying again.");
1648
		unlink_if_exists($db_path);
1649
		try {
1650
			$DB = new SQLite3($db_path);
1651
			$DB->busyTimeout(60000);
1652
		} catch (Exception $e) {
1653
			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.");
1654
			return;
1655
		}
1656
	}
1657

    
1658
	if (!$DB) {
1659
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Trying again.");
1660
		unlink_if_exists($db_path);
1661
		$DB = new SQLite3($db_path);
1662
		$DB->busyTimeout(60000);
1663
		if (!$DB) {
1664
			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.");
1665
			return;
1666
		}
1667
	}
1668

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

    
1672
		/* If unable to initialize the database, reset and try again. */
1673
		$DB->close();
1674
		unset($DB);
1675
		unlink_if_exists($db_path);
1676
		$DB = new SQLite3($db_path);
1677
		$DB->busyTimeout(60000);
1678
		if ($DB->exec($createquery)) {
1679
			captiveportal_syslog("Successfully reinitialized tables for {$cpzone} -- database has been reset.");
1680
			if (!is_numericint($cpzoneid)) {
1681
				if (is_array($config['captiveportal'])) {
1682
					foreach ($config['captiveportal'] as $cpkey => $cp) {
1683
						if ($cpzone == $cpkey) {
1684
							$cpzoneid = $cp['zoneid'];
1685
						}
1686
					}
1687
				}
1688
			}
1689
			if (is_numericint($cpzoneid)) {
1690
				$table_names = captiveportal_get_ipfw_table_names();
1691
				foreach ($table_names as $table_name) {
1692
					mwexec("/sbin/ipfw table {$table_name} flush");
1693
				}
1694
				captiveportal_syslog("Flushed tables for {$cpzone} after database reset.");
1695
			}
1696
		} else {
1697
			captiveportal_syslog("Still unable to create tables for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Remove the database file manually and try again.");
1698
		}
1699
	}
1700

    
1701
	return $DB;
1702
}
1703

    
1704
/* Get all tables for specific cpzone */
1705
function captiveportal_get_ipfw_table_names() {
1706
	global $cpzone;
1707

    
1708
	$result = array();
1709
	$tables = pfSense_ipfw_tables_list();
1710

    
1711
	if (!is_array($tables)) {
1712
		return $result;
1713
	}
1714

    
1715
	$len = strlen($cpzone) + 1;
1716
	foreach ($tables as $table) {
1717
		if (substr($table['name'], 0, $len) != $cpzone . '_') {
1718
			continue;
1719
		}
1720

    
1721
		$result[] = $table['name'];
1722
	}
1723

    
1724
	return $result;
1725
}
1726

    
1727
/* read captive portal DB into array */
1728
function captiveportal_read_db($query = "") {
1729
	$cpdb = array();
1730

    
1731
	$DB = captiveportal_opendb();
1732
	if ($DB) {
1733
		$response = $DB->query("SELECT * FROM captiveportal {$query}");
1734
		if ($response != FALSE) {
1735
			while ($row = $response->fetchArray()) {
1736
				$cpdb[] = $row;
1737
			}
1738
		}
1739
		$DB->close();
1740
	}
1741

    
1742
	return $cpdb;
1743
}
1744

    
1745
function captiveportal_remove_entries($remove) {
1746

    
1747
	if (!is_array($remove) || empty($remove)) {
1748
		return;
1749
	}
1750

    
1751
	$query = "DELETE FROM captiveportal WHERE sessionid in (";
1752
	foreach ($remove as $idx => $unindex) {
1753
		$query .= "'{$unindex}'";
1754
		if ($idx < (count($remove) - 1)) {
1755
			$query .= ",";
1756
		}
1757
	}
1758
	$query .= ")";
1759
	captiveportal_write_db($query);
1760
}
1761

    
1762
/* write captive portal DB */
1763
function captiveportal_write_db($queries) {
1764
	global $g;
1765

    
1766
	if (is_array($queries)) {
1767
		$query = implode(";", $queries);
1768
	} else {
1769
		$query = $queries;
1770
	}
1771

    
1772
	$DB = captiveportal_opendb();
1773
	if ($DB) {
1774
		$DB->exec("BEGIN TRANSACTION");
1775
		$result = $DB->exec($query);
1776
		if (!$result) {
1777
			captiveportal_syslog("Trying to modify DB returned error: {$DB->lastErrorMsg()}");
1778
		} else {
1779
			$DB->exec("END TRANSACTION");
1780
		}
1781
		$DB->close();
1782
		return $result;
1783
	} else {
1784
		return true;
1785
	}
1786
}
1787

    
1788
function captiveportal_write_elements() {
1789
	global $g, $config, $cpzone;
1790

    
1791
	$cpcfg = $config['captiveportal'][$cpzone];
1792

    
1793
	if (!is_dir($g['captiveportal_element_path'])) {
1794
		@mkdir($g['captiveportal_element_path']);
1795
	}
1796

    
1797
	if (is_array($cpcfg['element'])) {
1798
		foreach ($cpcfg['element'] as $data) {
1799
			/* Do not attempt to decode or write out empty files. */
1800
			if (empty($data['content']) || empty(base64_decode($data['content']))) {
1801
				unlink_if_exists("{$g['captiveportal_element_path']}/{$data['name']}");
1802
				touch("{$g['captiveportal_element_path']}/{$data['name']}");
1803
			} elseif (!@file_put_contents("{$g['captiveportal_element_path']}/{$data['name']}", base64_decode($data['content']))) {
1804
				printf(gettext('Error: cannot open \'%1$s\' in captiveportal_write_elements()%2$s'), $data['name'], "\n");
1805
				return 1;
1806
			}
1807
			if (!file_exists("{$g['captiveportal_path']}/{$data['name']}")) {
1808
				@symlink("{$g['captiveportal_element_path']}/{$data['name']}", "{$g['captiveportal_path']}/{$data['name']}");
1809
			}
1810
		}
1811
	}
1812

    
1813
	return 0;
1814
}
1815

    
1816
function captiveportal_free_dnrules($rulenos_start = 2000,
1817
    $rulenos_range_max = 64500, $dry_run = false) {
1818
	global $g, $cpzone;
1819

    
1820
	$removed_pipes = array();
1821

    
1822
	if (!file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1823
		return $removed_pipes;
1824
	}
1825

    
1826
	if (!$dry_run) {
1827
		$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1828
	}
1829

    
1830
	$rules = unserialize(file_get_contents(
1831
	    "{$g['vardb_path']}/captiveportaldn.rules"));
1832
	$ridx = $rulenos_start;
1833
	while ($ridx < $rulenos_range_max) {
1834
		if ($rules[$ridx] == $cpzone) {
1835
			if (!$dry_run) {
1836
				$rules[$ridx] = false;
1837
			}
1838
			$removed_pipes[] = $ridx;
1839
			$ridx++;
1840
			if (!$dry_run) {
1841
				$rules[$ridx] = false;
1842
			}
1843
			$removed_pipes[] = $ridx;
1844
			$ridx++;
1845
		} else {
1846
			$ridx += 2;
1847
		}
1848
	}
1849

    
1850
	if (!$dry_run) {
1851
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules",
1852
		    serialize($rules));
1853
		unlock($cpruleslck);
1854
	}
1855

    
1856
	unset($rules);
1857

    
1858
	return $removed_pipes;
1859
}
1860

    
1861
function captiveportal_get_next_dn_ruleno($rulenos_start = 2000, $rulenos_range_max = 64500) {
1862
	global $config, $g, $cpzone;
1863

    
1864
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1865
	$ruleno = 0;
1866
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1867
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1868
		$ridx = $rulenos_start;
1869
		while ($ridx < $rulenos_range_max) {
1870
			if (empty($rules[$ridx])) {
1871
				$ruleno = $ridx;
1872
				$rules[$ridx] = $cpzone;
1873
				$ridx++;
1874
				$rules[$ridx] = $cpzone;
1875
				break;
1876
			} else {
1877
				$ridx += 2;
1878
			}
1879
		}
1880
	} else {
1881
		$rules = array_pad(array(), $rulenos_range_max, false);
1882
		$ruleno = $rulenos_start;
1883
		$rules[$rulenos_start] = $cpzone;
1884
		$rulenos_start++;
1885
		$rules[$rulenos_start] = $cpzone;
1886
	}
1887
	file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1888
	unlock($cpruleslck);
1889
	unset($rules);
1890

    
1891
	return $ruleno;
1892
}
1893

    
1894
function captiveportal_free_dn_ruleno($ruleno) {
1895
	global $config, $g;
1896

    
1897
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1898
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1899
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1900
		$rules[$ruleno] = false;
1901
		$ruleno++;
1902
		$rules[$ruleno] = false;
1903
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1904
		unset($rules);
1905
	}
1906
	unlock($cpruleslck);
1907
}
1908

    
1909
function captiveportal_get_dn_passthru_ruleno($value) {
1910
	global $config, $g, $cpzone, $cpzoneid;
1911

    
1912
	$cpcfg = $config['captiveportal'][$cpzone];
1913
	if (!isset($cpcfg['enable'])) {
1914
		return NULL;
1915
	}
1916

    
1917
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1918
	$ruleno = NULL;
1919
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1920
		unset($output);
1921
		$item = pfSense_ipfw_table_lookup("{$cpzone}_pipe_mac",
1922
		    "any,{$value}");
1923
		if (!is_array($item) || empty($item['pipe'])) {
1924
			unlock($cpruleslck);
1925
			return NULL;
1926
		}
1927

    
1928
		$ruleno = intval($item['pipe']);
1929
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1930
		if (!$rules[$ruleno]) {
1931
			$ruleno = NULL;
1932
		}
1933
		unset($rules);
1934
	}
1935
	unlock($cpruleslck);
1936

    
1937
	return $ruleno;
1938
}
1939

    
1940
/**
1941
 * This function will calculate the traffic produced by a client
1942
 * based on its firewall rule
1943
 *
1944
 * Point of view: NAS
1945
 *
1946
 * Input means: from the client
1947
 * Output means: to the client
1948
 *
1949
 */
1950

    
1951
function getVolume($ip) {
1952
	global $config, $cpzone;
1953

    
1954
	$reverse = isset($config['captiveportal'][$cpzone]['reverseacct'])
1955
	    ? true : false;
1956
	$volume = array();
1957
	// Initialize vars properly, since we don't want NULL vars
1958
	$volume['input_pkts'] = $volume['input_bytes'] = 0;
1959
	$volume['output_pkts'] = $volume['output_bytes'] = 0;
1960

    
1961
	$tables = array("allowed", "auth");
1962

    
1963
	foreach($tables as $table) {
1964
		$ipfw = pfSense_ipfw_table_lookup("{$cpzone}_{$table}_up", $ip);
1965
		if (!is_array($ipfw)) {
1966
			continue;
1967
		}
1968
		if ($reverse) {
1969
			$volume['output_pkts'] = $ipfw['packets'];
1970
			$volume['output_bytes'] = $ipfw['bytes'];
1971
		} else {
1972
			$volume['input_pkts'] = $ipfw['packets'];
1973
			$volume['input_bytes'] = $ipfw['bytes'];
1974
		}
1975
	}
1976

    
1977
	foreach($tables as $table) {
1978
		$ipfw = pfSense_ipfw_table_lookup("{$cpzone}_{$table}_down",
1979
		    $ip);
1980
		if (!is_array($ipfw)) {
1981
			continue;
1982
		}
1983
		if ($reverse) {
1984
			$volume['input_pkts'] = $ipfw['packets'];
1985
			$volume['input_bytes'] = $ipfw['bytes'];
1986
		} else {
1987
			$volume['output_pkts'] = $ipfw['packets'];
1988
			$volume['output_bytes'] = $ipfw['bytes'];
1989
		}
1990
	}
1991

    
1992
	return $volume;
1993
}
1994

    
1995
/**
1996
 * Get the NAS-IP-Address based on the current wan address
1997
 *
1998
 * Use functions in interfaces.inc to find this out
1999
 *
2000
 */
2001

    
2002
function getNasIP() {
2003
	global $config, $cpzone;
2004

    
2005
	if (empty($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
2006
			$nasIp = get_interface_ip();
2007
	} else {
2008
		if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
2009
			$nasIp = $config['captiveportal'][$cpzone]['radiussrcip_attribute'];
2010
		} else {
2011
			$nasIp = get_interface_ip($config['captiveportal'][$cpzone]['radiussrcip_attribute']);
2012
		}
2013
	}
2014

    
2015
	if (!is_ipaddr($nasIp)) {
2016
		$nasIp = "0.0.0.0";
2017
	}
2018

    
2019
	return $nasIp;
2020
}
2021

    
2022
function portal_ip_from_client_ip($cliip) {
2023
	global $config, $cpzone;
2024

    
2025
	$isipv6 = is_ipaddrv6($cliip);
2026
	$interfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
2027
	foreach ($interfaces as $cpif) {
2028
		if ($isipv6) {
2029
			$ip = get_interface_ipv6($cpif);
2030
			$sn = get_interface_subnetv6($cpif);
2031
		} else {
2032
			$ip = get_interface_ip($cpif);
2033
			$sn = get_interface_subnet($cpif);
2034
		}
2035
		if (ip_in_subnet($cliip, "{$ip}/{$sn}")) {
2036
			return $ip;
2037
		}
2038
	}
2039

    
2040
	$inet = ($isipv6) ? '-inet6' : '-inet';
2041
	$iface = exec_command("/sbin/route -n get {$inet} {$cliip} | /usr/bin/awk '/interface/ { print \$2; };'");
2042
	$iface = trim($iface, "\n");
2043
	if (!empty($iface)) {
2044
		$ip = ($isipv6) ? find_interface_ipv6($iface) : find_interface_ip($iface);
2045
		if (is_ipaddr($ip)) {
2046
			return $ip;
2047
		}
2048
	}
2049

    
2050
	// doesn't match up to any particular interface
2051
	// so let's set the portal IP to what PHP says
2052
	// the server IP issuing the request is.
2053
	// allows same behavior as 1.2.x where IP isn't
2054
	// in the subnet of any CP interface (static routes, etc.)
2055
	// rather than forcing to DNS hostname resolution
2056
	$ip = $_SERVER['SERVER_ADDR'];
2057
	if (is_ipaddr($ip)) {
2058
		return $ip;
2059
	}
2060

    
2061
	return false;
2062
}
2063

    
2064
function portal_hostname_from_client_ip($cliip) {
2065
	global $config, $cpzone;
2066

    
2067
	$cpcfg = $config['captiveportal'][$cpzone];
2068

    
2069
	if (isset($cpcfg['httpslogin'])) {
2070
		$listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 8001);
2071
		$ourhostname = $cpcfg['httpsname'];
2072

    
2073
		if ($listenporthttps != 443) {
2074
			$ourhostname .= ":" . $listenporthttps;
2075
		}
2076
	} else {
2077
		$listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : ($cpcfg['zoneid'] + 8000);
2078
		$ifip = portal_ip_from_client_ip($cliip);
2079
		if (!$ifip) {
2080
			$ourhostname = "{$config['system']['hostname']}.{$config['system']['domain']}";
2081
		} else {
2082
			$ourhostname = (is_ipaddrv6($ifip)) ? "[{$ifip}]" : "{$ifip}";
2083
		}
2084

    
2085
		if ($listenporthttp != 80) {
2086
			$ourhostname .= ":" . $listenporthttp;
2087
		}
2088
	}
2089

    
2090
	return $ourhostname;
2091
}
2092

    
2093
/* functions move from index.php */
2094

    
2095
function portal_reply_page($redirurl, $type = null, $message = null, $clientmac = null, $clientip = null, $username = null, $password = null) {
2096
	global $g, $config, $cpzone;
2097

    
2098
	/* Get captive portal layout */
2099
	if ($type == "redir") {
2100
		header("Location: {$redirurl}");
2101
		return;
2102
	} else if ($type == "login") {
2103
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
2104
	} else {
2105
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
2106
	}
2107

    
2108
	$cpcfg = $config['captiveportal'][$cpzone];
2109

    
2110
	/* substitute the PORTAL_REDIRURL variable */
2111
	if ($cpcfg['preauthurl']) {
2112
		$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
2113
		$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
2114
	}
2115

    
2116
	/* substitute other variables */
2117
	$ourhostname = portal_hostname_from_client_ip($clientip);
2118
	$protocol = (isset($cpcfg['httpslogin'])) ? 'https://' : 'http://';
2119
	$htmltext = str_replace("\$PORTAL_ACTION\$", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
2120
	$htmltext = str_replace("#PORTAL_ACTION#", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
2121

    
2122
	$htmltext = str_replace("\$PORTAL_ZONE\$", htmlspecialchars($cpzone), $htmltext);
2123
	$htmltext = str_replace("\$PORTAL_REDIRURL\$", htmlspecialchars($redirurl), $htmltext);
2124
	$htmltext = str_replace("\$PORTAL_MESSAGE\$", htmlspecialchars($message), $htmltext);
2125
	$htmltext = str_replace("\$CLIENT_MAC\$", htmlspecialchars($clientmac), $htmltext);
2126
	$htmltext = str_replace("\$CLIENT_IP\$", htmlspecialchars($clientip), $htmltext);
2127

    
2128
	// Special handling case for captive portal master page so that it can be ran
2129
	// through the PHP interpreter using the include method above.  We convert the
2130
	// $VARIABLE$ case to #VARIABLE# in /etc/inc/captiveportal.inc before writing out.
2131
	$htmltext = str_replace("#PORTAL_ZONE#", htmlspecialchars($cpzone), $htmltext);
2132
	$htmltext = str_replace("#PORTAL_REDIRURL#", htmlspecialchars($redirurl), $htmltext);
2133
	$htmltext = str_replace("#PORTAL_MESSAGE#", htmlspecialchars($message), $htmltext);
2134
	$htmltext = str_replace("#CLIENT_MAC#", htmlspecialchars($clientmac), $htmltext);
2135
	$htmltext = str_replace("#CLIENT_IP#", htmlspecialchars($clientip), $htmltext);
2136
	$htmltext = str_replace("#USERNAME#", htmlspecialchars($username), $htmltext);
2137
	$htmltext = str_replace("#PASSWORD#", htmlspecialchars($password), $htmltext);
2138

    
2139
	echo $htmltext;
2140
}
2141

    
2142
function portal_mac_radius($clientmac, $clientip) {
2143
	global $config, $cpzone;
2144

    
2145
	$radmac_secret = $config['captiveportal'][$cpzone]['radmac_secret'];
2146

    
2147
	/* authentication against the radius server */
2148
	$username = mac_format($clientmac);
2149
	$auth_list = radius($username, $radmac_secret, $clientip, $clientmac, "MACHINE LOGIN");
2150
	if ($auth_list['auth_val'] == 2) {
2151
		return TRUE;
2152
	}
2153

    
2154
	if (!empty($auth_list['url_redirection'])) {
2155
		portal_reply_page($auth_list['url_redirection'], "redir");
2156
	}
2157

    
2158
	return FALSE;
2159
}
2160

    
2161
function captiveportal_reapply_attributes($cpentry, $attributes) {
2162
	global $config, $cpzone, $g;
2163

    
2164
	if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2165
		$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2166
		$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2167
	} else {
2168
		$dwfaultbw_up = $dwfaultbw_down = 0;
2169
	}
2170
	/* pipe throughputs must always be an integer, enforce that restriction again here. */
2171
	if (isset($config['captiveportal'][$cpzone]['radiusperuserbw'])) {
2172
		$bw_up = round(!empty($attributes['bw_up']) ? intval($attributes['bw_up'])/1000 : $dwfaultbw_up, 0);
2173
		$bw_down = round(!empty($attributes['bw_down']) ? intval($attributes['bw_down'])/1000 : $dwfaultbw_down, 0);
2174
	} else {
2175
		$bw_up = round($dwfaultbw_up,0);
2176
		$bw_down = round($dwfaultbw_down,0);
2177
	}
2178

    
2179
	$bw_up_pipeno = $cpentry[1];
2180
	$bw_down_pipeno = $cpentry[1]+1;
2181

    
2182
	$_gb = @pfSense_ipfw_pipe("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2183
	$_gb = @pfSense_ipfw_pipe("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2184
	//captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "RADIUS_BANDWIDTH_REAPPLY", "{$bw_up}/{$bw_down}");
2185

    
2186
	unset($bw_up_pipeno, $bw_down_pipeno, $bw_up, $bw_down);
2187
}
2188

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

    
2192
	// Ensure we create an array if we are missing attributes
2193
	if (!is_array($attributes)) {
2194
		$attributes = array();
2195
	}
2196

    
2197
	unset($sessionid);
2198

    
2199
	/* Do not allow concurrent login execution. */
2200
	$cpdblck = lock("captiveportaldb{$cpzone}", LOCK_EX);
2201

    
2202
	if ($attributes['voucher']) {
2203
		$remaining_time = $attributes['session_timeout'];
2204
	// Set RADIUS-Attribute to Voucher to prevent ReAuth-Reqeuest for Vouchers Bug: #2155
2205
		$radiusctx="voucher";
2206
	}
2207

    
2208
	$writecfg = false;
2209
	/* Find an existing session */
2210
	if ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) &&
2211
	    $passthrumac &&
2212
	    isset($config['captiveportal'][$cpzone]['passthrumacadd'])) {
2213
		$mac = captiveportal_passthrumac_findbyname($username);
2214
		if (!empty($mac) && $_POST['replacemacpassthru']) {
2215
			foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $idx => $macent) {
2216
				if ($macent['mac'] != $mac['mac']) {
2217
					continue;
2218
				}
2219

    
2220
				$macrules = "";
2221
				$pipeno = captiveportal_get_dn_passthru_ruleno($mac['mac']);
2222
				if ($pipeno) {
2223
					captiveportal_free_dn_ruleno($pipeno);
2224
					$macrules .= "table {$cpzone}_pipe_mac delete any,{$mac['mac']}\n";
2225
					$macrules .= "table {$cpzone}_pipe_mac delete {$mac['mac']},any\n";
2226
					$macrules .= "pipe delete {$pipeno}\n";
2227
					++$pipeno;
2228
					$macrules .= "pipe delete {$pipeno}\n";
2229
				}
2230
				unset($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
2231
				$mac['action'] = 'pass';
2232
				$mac['mac'] = $clientmac;
2233
				$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2234
				$macrules .= captiveportal_passthrumac_configure_entry($mac);
2235
				file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2236
				mwexec("/sbin/ipfw -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2237
				$writecfg = true;
2238
				$sessionid = true;
2239
				break;
2240
			}
2241
		} elseif (!empty($mac)) {
2242
			portal_reply_page($redirurl, "error", "Username: {$username} is already authenticated using another MAC address.",
2243
				$clientmac, $clientip, $username, $password);
2244
			unlock($cpdblck);
2245
			return;
2246
		}
2247
	}
2248

    
2249
	/* read in client database */
2250
	$query = "WHERE ip = '{$clientip}'";
2251
	$tmpusername = SQLite3::escapeString(strtolower($username));
2252
	if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
2253
		$query .= " OR (username != 'unauthenticated' AND lower(username) = '{$tmpusername}')";
2254
	}
2255
	$cpdb = captiveportal_read_db($query);
2256

    
2257
	/* Snapshot the timestamp */
2258
	$allow_time = time();
2259
	$radiusservers = captiveportal_get_radius_servers();
2260
	$unsetindexes = array();
2261
	if (is_null($radiusctx)) {
2262
		$radiusctx = 'first';
2263
	}
2264

    
2265
	foreach ($cpdb as $cpentry) {
2266
		if (empty($cpentry[12])) {
2267
			$cpentry[12] = 'first';
2268
		}
2269
		/* on the same ip */
2270
		if ($cpentry[2] == $clientip) {
2271
			if (isset($config['captiveportal'][$cpzone]['nomacfilter']) || $cpentry[3] == $clientmac) {
2272
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING OLD SESSION");
2273
			} else {
2274
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING IP {$cpentry[2]} WITH DIFFERENT MAC ADDRESS {$cpentry[3]}");
2275
			}
2276
			$sessionid = $cpentry[5];
2277
			break;
2278
		} elseif (($attributes['voucher']) && ($username != 'unauthenticated') && ($cpentry[4] == $username)) {
2279
			// user logged in with an active voucher. Check for how long and calculate
2280
			// how much time we can give him (voucher credit - used time)
2281
			$remaining_time = $cpentry[0] + $cpentry[7] - $allow_time;
2282
			if ($remaining_time < 0) { // just in case.
2283
				$remaining_time = 0;
2284
			}
2285

    
2286
			/* This user was already logged in so we disconnect the old one */
2287
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[12]], 13);
2288
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2289
			$unsetindexes[] = $cpentry[5];
2290
			break;
2291
		} elseif ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && ($username != 'unauthenticated')) {
2292
			/* on the same username */
2293
			if (strcasecmp($cpentry[4], $username) == 0) {
2294
				/* This user was already logged in so we disconnect the old one */
2295
				captiveportal_disconnect($cpentry, $radiusservers[$cpentry[12]], 13);
2296
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2297
				$unsetindexes[] = $cpentry[5];
2298
				break;
2299
			}
2300
		}
2301
	}
2302
	unset($cpdb);
2303

    
2304
	if (!empty($unsetindexes)) {
2305
		captiveportal_remove_entries($unsetindexes);
2306
	}
2307

    
2308
	if ($attributes['voucher'] && $remaining_time <= 0) {
2309
		return 0;       // voucher already used and no time left
2310
	}
2311

    
2312
	if (!isset($sessionid)) {
2313
		/* generate unique session ID */
2314
		$tod = gettimeofday();
2315
		$sessionid = substr(md5(mt_rand() . $tod['sec'] . $tod['usec'] . $clientip . $clientmac), 0, 16);
2316

    
2317
		if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2318
			$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2319
			$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2320
		} else {
2321
			$dwfaultbw_up = $dwfaultbw_down = 0;
2322
		}
2323
		/* pipe throughputs must always be an integer, enforce that restriction again here. */
2324
		if (isset($config['captiveportal'][$cpzone]['radiusperuserbw'])) {
2325
			$bw_up = round(!empty($attributes['bw_up']) ? intval($attributes['bw_up'])/1000 : $dwfaultbw_up, 0);
2326
			$bw_down = round(!empty($attributes['bw_down']) ? intval($attributes['bw_down'])/1000 : $dwfaultbw_down, 0);
2327
		} else {
2328
			$bw_up = round($dwfaultbw_up,0);
2329
			$bw_down = round($dwfaultbw_down,0);
2330
		}
2331

    
2332
		if ($passthrumac) {
2333

    
2334
			$mac = array();
2335
			$mac['action'] = 'pass';
2336
			$mac['mac'] = $clientmac;
2337
			$mac['ip'] = $clientip; /* Used only for logging */
2338
			if (isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
2339
				$mac['username'] = $username;
2340
				if ($attributes['voucher']) {
2341
					$mac['logintype'] = "voucher";
2342
				}
2343
			}
2344
			if ($username == "unauthenticated") {
2345
				$mac['descr'] = "Auto-added";
2346
			} else {
2347
				$mac['descr'] = "Auto-added for user {$username}";
2348
			}
2349
			if (!empty($bw_up)) {
2350
				$mac['bw_up'] = $bw_up;
2351
			}
2352
			if (!empty($bw_down)) {
2353
				$mac['bw_down'] = $bw_down;
2354
			}
2355
			if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2356
				$config['captiveportal'][$cpzone]['passthrumac'] = array();
2357
			}
2358
			//check for mac duplicates before adding it to config.
2359
			$mac_duplicate = false;
2360
			foreach($config['captiveportal'][$cpzone]['passthrumac'] as $mac_check){
2361
				if($mac_check['mac'] == $mac['mac']){
2362
					$mac_duplicate = true;
2363
				}
2364
			}
2365
			if(!$mac_duplicate){
2366
				$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2367
			}
2368
			unlock($cpdblck);
2369
			$macrules = captiveportal_passthrumac_configure_entry($mac);
2370
			file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2371
			mwexec("/sbin/ipfw -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2372
			$writecfg = true;
2373
		} else {
2374
			/* See if a pipeno is passed, if not start sessions because this means there isn't one atm */
2375
			if (is_null($pipeno)) {
2376
				$pipeno = captiveportal_get_next_dn_ruleno();
2377
			}
2378

    
2379
			/* if the pool is empty, return appropriate message and exit */
2380
			if (is_null($pipeno)) {
2381
				portal_reply_page($redirurl, "error", "System reached maximum login capacity");
2382
				log_error("Zone: {$cpzone} - WARNING!  Captive portal has reached maximum login capacity");
2383
				unlock($cpdblck);
2384
				return;
2385
			}
2386

    
2387
			$bw_up_pipeno = $pipeno;
2388
			$bw_down_pipeno = $pipeno + 1;
2389
			//$bw_up /= 1000; // Scale to Kbit/s
2390
			$_gb = @pfSense_ipfw_pipe("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2391
			$_gb = @pfSense_ipfw_pipe("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2392

    
2393
			$rule_entry = "{$clientip}/" . (is_ipaddrv6($clientip) ? "128" : "32");
2394
			if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) {
2395
				$rule_entry .= ",{$clientmac}";
2396
			}
2397
			$_gb = @pfSense_ipfw_table("{$cpzone}_auth_up", IP_FW_TABLE_XADD, "{$rule_entry}", $bw_up_pipeno);
2398
			$_gb = @pfSense_ipfw_table("{$cpzone}_auth_down", IP_FW_TABLE_XADD, "{$rule_entry}", $bw_down_pipeno);
2399

    
2400
			if ($attributes['voucher']) {
2401
				$attributes['session_timeout'] = $remaining_time;
2402
			}
2403

    
2404
			/* handle empty attributes */
2405
			$session_timeout = (!empty($attributes['session_timeout'])) ? $attributes['session_timeout'] : 'NULL';
2406
			$idle_timeout = (!empty($attributes['idle_timeout'])) ? $attributes['idle_timeout'] : 'NULL';
2407
			$session_terminate_time = (!empty($attributes['session_terminate_time'])) ? $attributes['session_terminate_time'] : 'NULL';
2408
			$interim_interval = (!empty($attributes['interim_interval'])) ? $attributes['interim_interval'] : 'NULL';
2409
			$traffic_quota = (!empty($attributes['maxbytes'])) ? $attributes['maxbytes'] : 'NULL';
2410

    
2411
			/* escape username */
2412
			$safe_username = SQLite3::escapeString($username);
2413

    
2414
			/* encode password in Base64 just in case it contains commas */
2415
			$bpassword = (isset($config['captiveportal'][$cpzone]['reauthenticate'])) ? base64_encode($password) : '';
2416
			$insertquery = "INSERT INTO captiveportal (allow_time, pipeno, ip, mac, username, sessionid, bpassword, session_timeout, idle_timeout, session_terminate_time, interim_interval, traffic_quota, radiusctx) ";
2417
			$insertquery .= "VALUES ({$allow_time}, {$pipeno}, '{$clientip}', '{$clientmac}', '{$safe_username}', '{$sessionid}', '{$bpassword}', ";
2418
			$insertquery .= "{$session_timeout}, {$idle_timeout}, {$session_terminate_time}, {$interim_interval}, {$traffic_quota}, '{$radiusctx}')";
2419

    
2420
			/* store information to database */
2421
			captiveportal_write_db($insertquery);
2422
			unlock($cpdblck);
2423
			unset($insertquery, $bpassword);
2424

    
2425
			if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers[$radiusctx])) {
2426
				$acct_val = RADIUS_ACCOUNTING_START($pipeno, $username, $sessionid, $radiusservers[$radiusctx], $clientip, $clientmac);
2427
				if ($acct_val == 1) {
2428
					captiveportal_logportalauth($username, $clientmac, $clientip, $type, "RADIUS ACCOUNTING FAILED");
2429
				}
2430
			}
2431
		}
2432
	} else {
2433
		/* NOTE: #3062-11 If the pipeno has been allocated free it to not DoS the CP and maintain proper operation as in radius() case */
2434
		if (!is_null($pipeno)) {
2435
			captiveportal_free_dn_ruleno($pipeno);
2436
		}
2437

    
2438
		unlock($cpdblck);
2439
	}
2440

    
2441
	if ($writecfg == true) {
2442
		write_config(gettext("Captive Portal allowed users configuration changed"));
2443
	}
2444

    
2445
	/* redirect user to desired destination */
2446
	if (!empty($attributes['url_redirection'])) {
2447
		$my_redirurl = $attributes['url_redirection'];
2448
	} else if (!empty($redirurl)) {
2449
		$my_redirurl = $redirurl;
2450
	} else if (!empty($config['captiveportal'][$cpzone]['redirurl'])) {
2451
		$my_redirurl = $config['captiveportal'][$cpzone]['redirurl'];
2452
	}
2453

    
2454
	if (isset($config['captiveportal'][$cpzone]['logoutwin_enable']) && !$passthrumac) {
2455
		$ourhostname = portal_hostname_from_client_ip($clientip);
2456
		$protocol = (isset($config['captiveportal'][$cpzone]['httpslogin'])) ? 'https://' : 'http://';
2457
		$logouturl = "{$protocol}{$ourhostname}/";
2458

    
2459
		if (isset($attributes['reply_message'])) {
2460
			$message = $attributes['reply_message'];
2461
		} else {
2462
			$message = 0;
2463
		}
2464

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

    
2467
	} else {
2468
		portal_reply_page($my_redirurl, "redir", "Just redirect the user.");
2469
	}
2470

    
2471
	return $sessionid;
2472
}
2473

    
2474

    
2475
/*
2476
 * Used for when pass-through credits are enabled.
2477
 * Returns true when there was at least one free login to deduct for the MAC.
2478
 * Expired entries are removed as they are seen.
2479
 * Active entries are updated according to the configuration.
2480
 */
2481
function portal_consume_passthrough_credit($clientmac) {
2482
	global $config, $cpzone;
2483

    
2484
	if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count'])) {
2485
		$freeloginscount = $config['captiveportal'][$cpzone]['freelogins_count'];
2486
	} else {
2487
		return false;
2488
	}
2489

    
2490
	if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout'])) {
2491
		$resettimeout = $config['captiveportal'][$cpzone]['freelogins_resettimeout'];
2492
	} else {
2493
		return false;
2494
	}
2495

    
2496
	if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac) {
2497
		return false;
2498
	}
2499

    
2500
	$updatetimeouts = isset($config['captiveportal'][$cpzone]['freelogins_updatetimeouts']);
2501

    
2502
	/*
2503
	 * Read database of used MACs.  Lines are a comma-separated list
2504
	 * of the time, MAC, then the count of pass-through credits remaining.
2505
	 */
2506
	$usedmacs = captiveportal_read_usedmacs_db();
2507

    
2508
	$currenttime = time();
2509
	$found = false;
2510
	foreach ($usedmacs as $key => $usedmac) {
2511
		$usedmac = explode(",", $usedmac);
2512

    
2513
		if ($usedmac[1] == $clientmac) {
2514
			if ($usedmac[0] + ($resettimeout * 3600) > $currenttime) {
2515
				if ($usedmac[2] < 1) {
2516
					if ($updatetimeouts) {
2517
						$usedmac[0] = $currenttime;
2518
						unset($usedmacs[$key]);
2519
						$usedmacs[] = implode(",", $usedmac);
2520
						captiveportal_write_usedmacs_db($usedmacs);
2521
					}
2522

    
2523
					return false;
2524
				} else {
2525
					$usedmac[2] -= 1;
2526
					$usedmacs[$key] = implode(",", $usedmac);
2527
				}
2528

    
2529
				$found = true;
2530
			} else {
2531
				unset($usedmacs[$key]);
2532
			}
2533

    
2534
			break;
2535
		} else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime) {
2536
			unset($usedmacs[$key]);
2537
		}
2538
	}
2539

    
2540
	if (!$found) {
2541
		$usedmac = array($currenttime, $clientmac, $freeloginscount - 1);
2542
		$usedmacs[] = implode(",", $usedmac);
2543
	}
2544

    
2545
	captiveportal_write_usedmacs_db($usedmacs);
2546
	return true;
2547
}
2548

    
2549
function captiveportal_read_usedmacs_db() {
2550
	global $g, $cpzone;
2551

    
2552
	$cpumaclck = lock("captiveusedmacs{$cpzone}");
2553
	if (file_exists("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db")) {
2554
		$usedmacs = file("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2555
		if (!$usedmacs) {
2556
			$usedmacs = array();
2557
		}
2558
	} else {
2559
		$usedmacs = array();
2560
	}
2561

    
2562
	unlock($cpumaclck);
2563
	return $usedmacs;
2564
}
2565

    
2566
function captiveportal_write_usedmacs_db($usedmacs) {
2567
	global $g, $cpzone;
2568

    
2569
	$cpumaclck = lock("captiveusedmacs{$cpzone}", LOCK_EX);
2570
	@file_put_contents("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", implode("\n", $usedmacs));
2571
	unlock($cpumaclck);
2572
}
2573

    
2574
function captiveportal_blocked_mac($mac) {
2575
	global $config, $g, $cpzone;
2576

    
2577
	if (empty($mac) || !is_macaddr($mac)) {
2578
		return false;
2579
	}
2580

    
2581
	if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2582
		return false;
2583
	}
2584

    
2585
	foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) {
2586
		if (($passthrumac['action'] == 'block') &&
2587
		    ($passthrumac['mac'] == strtolower($mac))) {
2588
			return true;
2589
		}
2590
	}
2591

    
2592
	return false;
2593

    
2594
}
2595

    
2596
function captiveportal_send_server_accounting($off = false) {
2597
	global $cpzone, $config;
2598

    
2599
	if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
2600
		return;
2601
	}
2602
	if ($off) {
2603
		$racct = new Auth_RADIUS_Acct_Off;
2604
	} else {
2605
		$racct = new Auth_RADIUS_Acct_On;
2606
	}
2607
	$radiusservers = captiveportal_get_radius_servers();
2608
	if (empty($radiusservers)) {
2609
		return;
2610
	}
2611
	foreach ($radiusservers['first'] as $radsrv) {
2612
		// Add a new server to our instance
2613
		$racct->addServer($radsrv['ipaddr'], $radsrv['acctport'], $radsrv['key']);
2614
	}
2615
	if (PEAR::isError($racct->start())) {
2616
		$retvalue['acct_val'] = 1;
2617
		$retvalue['error'] = $racct->getMessage();
2618

    
2619
		// If we encounter an error immediately stop this function and go back
2620
		$racct->close();
2621
		return $retvalue;
2622
	}
2623
	// Send request
2624
	$result = $racct->send();
2625
	// Evaluation of the response
2626
	// 5 -> Accounting-Response
2627
	// See RFC2866 for this.
2628
	if (PEAR::isError($result)) {
2629
		$retvalue['acct_val'] = 1;
2630
		$retvalue['error'] = $result->getMessage();
2631
	} else if ($result === true) {
2632
		$retvalue['acct_val'] = 5 ;
2633
	} else {
2634
		$retvalue['acct_val'] = 1 ;
2635
	}
2636

    
2637
	$racct->close();
2638
	return $retvalue;
2639
}
2640

    
2641
function captiveportal_isip_logged($clientip) {
2642
	global $g, $cpzone;
2643

    
2644
	/* read in client database */
2645
	$query = "WHERE ip = '{$clientip}'";
2646
	$cpdb = captiveportal_read_db($query);
2647
	foreach ($cpdb as $cpentry) {
2648
		return $cpentry;
2649
	}
2650
}
2651
?>
(5-5/60)