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_accounting.inc");
31
require_once("radius_authentication.inc");
32
require_once("voucher.inc");
33

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

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

    
89
EOD;
90

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

    
99
EOD;
100
	}
101

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

    
130
EOD;
131

    
132
	return $htmltext;
133
}
134

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
304
EOD;
305
		}
306

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

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

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

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

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

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

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

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

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

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

    
353
		captiveportal_filterdns_configure();
354

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

    
362
		captiveportal_delete_rules($pipes_to_remove);
363

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

    
383
	unlock($captiveportallck);
384

    
385
	return 0;
386
}
387

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
512
	return $rule;
513
}
514

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

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

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

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

    
530
	captiveportal_load_modules();
531
	captiveportal_init_general_rules();
532

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

    
537
	$skipto = captiveportal_ipfw_ruleno($cpzoneid);
538

    
539
	$cprules = '';
540

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

    
554
		$cpipm = get_interface_ip($cpifgrp);
555

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
683
	captiveportal_filterdns_configure();
684

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

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

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

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

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

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

    
712
	$tables = captiveportal_get_ipfw_table_names();
713

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

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

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

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

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

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

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

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

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

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

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

    
772
	$radiussrvs = captiveportal_get_radius_servers();
773

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

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

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

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

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

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

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

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

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

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

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

    
945
	captiveportal_prune_old_automac();
946

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

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

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

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

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

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

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

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

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

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

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

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

    
1105
}
1106

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

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

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

    
1117
	/* find entry */
1118
	if (!empty($result)) {
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
		captiveportal_write_db("DELETE FROM captiveportal WHERE sessionid = '{$sessionid}'");
1128
		unset($result);
1129
	}
1130
}
1131

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

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

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

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

    
1149
	captiveportal_radius_stop_all($term_cause, $logoutReason);
1150

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

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

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

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

    
1169
	$cpdb = captiveportal_read_db();
1170

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

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

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

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

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

    
1218
		$pipeno = captiveportal_get_next_dn_ruleno();
1219

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

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

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

    
1238
	return $rules;
1239
}
1240

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

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

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

    
1257
	return $rules;
1258
}
1259

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

    
1263
	$rules = "";
1264

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

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

    
1296
	return $rules;
1297
}
1298

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

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

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

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

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

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

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

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

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

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

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

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

    
1395
	return $rules;
1396
}
1397

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

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

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

    
1421
	return $rules;
1422
}
1423

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

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

    
1434
	return $rules;
1435
}
1436

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

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

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

    
1456
	return 0;
1457
}
1458

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1591
	$pipeno = captiveportal_get_next_dn_ruleno();
1592

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

    
1601
	$radiusservers = captiveportal_get_radius_servers();
1602

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

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

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

    
1627
	return $auth_list;
1628
}
1629

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

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

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

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

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

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

    
1702
	return $DB;
1703
}
1704

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

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

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

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

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

    
1725
	return $result;
1726
}
1727

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

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

    
1743
	return $cpdb;
1744
}
1745

    
1746
function captiveportal_remove_entries($remove) {
1747

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

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

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

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

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

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

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

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

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

    
1814
	return 0;
1815
}
1816

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

    
1821
	$removed_pipes = array();
1822

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

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

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

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

    
1857
	unset($rules);
1858

    
1859
	return $removed_pipes;
1860
}
1861

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

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

    
1892
	return $ruleno;
1893
}
1894

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

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

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

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

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

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

    
1938
	return $ruleno;
1939
}
1940

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

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

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

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

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

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

    
1993
	return $volume;
1994
}
1995

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

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

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

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

    
2020
	return $nasIp;
2021
}
2022

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

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

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

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

    
2062
	return false;
2063
}
2064

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

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

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

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

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

    
2091
	return $ourhostname;
2092
}
2093

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

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

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

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

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

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

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

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

    
2140
	echo $htmltext;
2141
}
2142

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

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

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

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

    
2159
	return FALSE;
2160
}
2161

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

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

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

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

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

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

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

    
2198
	unset($sessionid);
2199

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

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

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

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

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

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

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

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

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

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

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

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

    
2333
		if ($passthrumac) {
2334

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

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

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

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

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

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

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

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

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

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

    
2439
		unlock($cpdblck);
2440
	}
2441

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

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

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

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

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

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

    
2472
	return $sessionid;
2473
}
2474

    
2475

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2593
	return false;
2594

    
2595
}
2596

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

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

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

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

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

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