Project

General

Profile

Download (82.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * captiveportal.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2018 Rubicon Communications, LLC (Netgate)
7
 * All rights reserved.
8
 *
9
 * originally part of m0n0wall (http://m0n0.ch/wall)
10
 * Copyright (c) 2003-2006 Manuel Kasper <mk@neon1.net>.
11
 * All rights reserved.
12
 *
13
 * Licensed under the Apache License, Version 2.0 (the "License");
14
 * you may not use this file except in compliance with the License.
15
 * You may obtain a copy of the License at
16
 *
17
 * http://www.apache.org/licenses/LICENSE-2.0
18
 *
19
 * Unless required by applicable law or agreed to in writing, software
20
 * distributed under the License is distributed on an "AS IS" BASIS,
21
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
 * See the License for the specific language governing permissions and
23
 * limitations under the License.
24
 */
25

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

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

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

    
88
EOD;
89

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

    
98
EOD;
99
	}
100

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

    
129
EOD;
130

    
131
	return $htmltext;
132
}
133

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
303
EOD;
304
		}
305

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

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

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

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

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

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

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

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

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

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

    
352
		captiveportal_filterdns_configure();
353

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

    
361
		captiveportal_delete_rules($pipes_to_remove);
362

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

    
382
	unlock($captiveportallck);
383

    
384
	return 0;
385
}
386

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
511
	return $rule;
512
}
513

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

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

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

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

    
529
	captiveportal_load_modules();
530
	captiveportal_init_general_rules();
531

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

    
536
	$skipto = captiveportal_ipfw_ruleno($cpzoneid);
537

    
538
	$cprules = '';
539

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

    
553
		$cpipm = get_interface_ip($cpifgrp);
554

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
682
	captiveportal_filterdns_configure();
683

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

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

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

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

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

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

    
711
	$tables = captiveportal_get_ipfw_table_names();
712

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

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

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

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

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

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

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

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

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

    
758
	/* Is there any job to do? */
759
	if (!$timeout && !$idletimeout && !isset($cpcfg['reauthenticate']) &&
760
	    !isset($cpcfg['radiussession_timeout']) && !isset($vcpcfg['enable'])) {
761
		return;
762
	}
763

    
764
	$radiussrvs = captiveportal_get_radius_servers();
765

    
766
	/* Read database */
767
	/* NOTE: while this can be simplified in non radius case keep as is for now */
768
	$cpdb = captiveportal_read_db();
769

    
770
	$unsetindexes = array();
771
	$voucher_needs_sync = false;
772
	/*
773
	 * Snapshot the time here to use for calculation to speed up the process.
774
	 * If something is missed next run will catch it!
775
	 */
776
	$pruning_time = time();
777
	foreach ($cpdb as $cpentry) {
778
		$stop_time = $pruning_time;
779

    
780
		$timedout = false;
781
		$term_cause = 1;
782
		if (empty($cpentry[11])) {
783
			$cpentry[11] = 'first';
784
		}
785
		$radiusservers = $radiussrvs[$cpentry[11]];
786

    
787
		/* hard timeout? */
788
		if ($timeout) {
789
			if (($pruning_time - $cpentry[0]) >= $timeout) {
790
				$timedout = true;
791
				$term_cause = 5; // Session-Timeout
792
			}
793
		}
794

    
795
		/* Session-Terminate-Time */
796
		if (!$timedout && !empty($cpentry[9])) {
797
			if ($pruning_time >= $cpentry[9]) {
798
				$timedout = true;
799
				$term_cause = 5; // Session-Timeout
800
			}
801
		}
802

    
803
		/* check if the radius idle_timeout attribute has been set and if its set change the idletimeout to this value */
804
		$uidletimeout = (is_numeric($cpentry[8])) ? $cpentry[8] : $idletimeout;
805
		/* if an idle timeout is specified, get last activity timestamp from ipfw */
806
		if (!$timedout && $uidletimeout > 0) {
807
			$lastact = captiveportal_get_last_activity($cpentry[2]);
808
			/*	If the user has logged on but not sent any traffic they will never be logged out.
809
			 *	We "fix" this by setting lastact to the login timestamp.
810
			 */
811
			$lastact = $lastact ? $lastact : $cpentry[0];
812
			if ($lastact && (($pruning_time - $lastact) >= $uidletimeout)) {
813
				$timedout = true;
814
				$term_cause = 4; // Idle-Timeout
815
				if (!isset($config['captiveportal'][$cpzone]['includeidletime'])) {
816
					$stop_time = $lastact;
817
				}
818
			}
819
		}
820

    
821
		/* if vouchers are configured, activate session timeouts */
822
		if (!$timedout && isset($vcpcfg['enable']) && !empty($cpentry[7])) {
823
			if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
824
				$timedout = true;
825
				$term_cause = 5; // Session-Timeout
826
				$voucher_needs_sync = true;
827
			}
828
		}
829

    
830
		/* if radius session_timeout is enabled and the session_timeout is not null, then check if the user should be logged out */
831
		if (!$timedout && isset($cpcfg['radiussession_timeout']) && !empty($cpentry[7])) {
832
			if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
833
				$timedout = true;
834
				$term_cause = 5; // Session-Timeout
835
			}
836
		}
837

    
838
		if ($timedout) {
839
			captiveportal_disconnect($cpentry, $radiusservers, $term_cause, $stop_time);
840
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "TIMEOUT");
841
			$unsetindexes[] = $cpentry[5];
842
		}
843

    
844
		/* do periodic RADIUS reauthentication? */
845
		if (!$timedout && !empty($radiusservers)) {
846
			if (isset($cpcfg['radacct_enable'])) {
847
				if (substr($cpcfg['reauthenticateacct'], 0, 9) == "stopstart") {
848
					/* stop and restart accounting */
849
					if ($cpcfg['reauthenticateacct'] == "stopstartfreeradius") {
850
						$rastart_time = 0;
851
						$rastop_time = 60;
852
					} else {
853
						$rastart_time = $cpentry[0];
854
						$rastop_time = null;
855
					}
856
					RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
857
						$cpentry[4], // username
858
						$cpentry[5], // sessionid
859
						$rastart_time, // start time
860
						$radiusservers,
861
						$cpentry[2], // clientip
862
						$cpentry[3], // clientmac
863
						10, // NAS Request
864
						false, // Not an interim request
865
						$rastop_time); // Stop Time
866
					$clientsn = (is_ipaddrv6($cpentry[2])) ? 128 : 32;
867
					pfSense_ipfw_table_zerocnt("{$cpzone}_auth_up", "{$cpentry[2]}/{$clientsn}");
868
					pfSense_ipfw_table_zerocnt("{$cpzone}_auth_down", "{$cpentry[2]}/{$clientsn}");
869
					if ($cpcfg['reauthenticateacct'] == "stopstartfreeradius") {
870
						/* Need to pause here or the FreeRADIUS server gets confused about packet ordering. */
871
						sleep(1);
872
					}
873
					RADIUS_ACCOUNTING_START($cpentry[1], // ruleno
874
						$cpentry[4], // username
875
						$cpentry[5], // sessionid
876
						$radiusservers,
877
						$cpentry[2], // clientip
878
						$cpentry[3]); // clientmac
879
				} else if ($cpcfg['reauthenticateacct'] == "interimupdate") {
880
					$session_time = $pruning_time - $cpentry[0];
881
					if (!empty($cpentry[10]) && $cpentry[10] > 60) {
882
						$interval = $cpentry[10];
883
					} else {
884
						$interval = 0;
885
					}
886
					$past_interval_min = ($session_time > $interval);
887
					if ($interval != 0) {
888
						$within_interval = ($session_time % $interval >= 0 && $session_time % $interval <= 59);
889
					}
890
					if ($interval === 0 || ($interval > 0 && $past_interval_min && $within_interval)) {
891
						RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
892
							$cpentry[4], // username
893
							$cpentry[5], // sessionid
894
							$cpentry[0], // start time
895
							$radiusservers,
896
							$cpentry[2], // clientip
897
							$cpentry[3], // clientmac
898
							10, // NAS Request
899
							true); // Interim Updates
900
					}
901
				}
902
			}
903

    
904
			/* check this user against RADIUS again */
905
			if (isset($cpcfg['reauthenticate'])) {
906
				$auth_list = RADIUS_AUTHENTICATION($cpentry[4], // username
907
					base64_decode($cpentry[6]), // password
908
					$radiusservers,
909
					$cpentry[2], // clientip
910
					$cpentry[3], // clientmac
911
					$cpentry[1]); // ruleno
912
				if ($auth_list['auth_val'] == 3) {
913
					captiveportal_disconnect($cpentry, $radiusservers, 17);
914
					captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "RADIUS_DISCONNECT", $auth_list['reply_message']);
915
					$unsetindexes[] = $cpentry[5];
916
				} else if ($auth_list['auth_val'] == 2) {
917
					captiveportal_reapply_attributes($cpentry, $auth_list);
918
				}
919
			}
920
		}
921
	}
922
	unset($cpdb);
923

    
924
	captiveportal_prune_old_automac();
925

    
926
	if ($voucher_needs_sync == true) {
927
		/* Trigger a sync of the vouchers on config */
928
		send_event("service sync vouchers");
929
	}
930

    
931
	/* write database */
932
	if (!empty($unsetindexes)) {
933
		captiveportal_remove_entries($unsetindexes);
934
	}
935
}
936

    
937
function captiveportal_prune_old_automac() {
938
	global $g, $config, $cpzone, $cpzoneid;
939

    
940
	if (is_array($config['captiveportal'][$cpzone]['passthrumac']) &&
941
	    isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
942
		$tmpvoucherdb = array();
943
		$macrules = "";
944
		$writecfg = false;
945
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $eid => $emac) {
946
			if ($emac['logintype'] != "voucher") {
947
				continue;
948
			}
949
			if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
950
				if (isset($tmpvoucherdb[$emac['username']])) {
951
					$temac = $config['captiveportal'][$cpzone]['passthrumac'][$tmpvoucherdb[$emac['username']]];
952
					$pipeno = captiveportal_get_dn_passthru_ruleno($temac['mac']);
953
					if ($pipeno) {
954
						captiveportal_free_dn_ruleno($pipeno);
955
						$macrules .= "table {$cpzone}_pipe_mac delete any,{$temac['mac']}\n";
956
						$macrules .= "table {$cpzone}_pipe_mac delete {$temac['mac']},any\n";
957
						$macrules .= "pipe delete {$pipeno}\n";
958
						++$pipeno;
959
						$macrules .= "pipe delete {$pipeno}\n";
960
					}
961
					$writecfg = true;
962
					captiveportal_logportalauth($temac['username'], $temac['mac'],
963
					    $temac['ip'], "DUPLICATE {$temac['username']} LOGIN - TERMINATING OLD SESSION");
964
					unset($config['captiveportal'][$cpzone]['passthrumac'][$tmpvoucherdb[$emac['username']]]);
965
				}
966
				$tmpvoucherdb[$emac['username']] = $eid;
967
			}
968
			if (voucher_auth($emac['username']) <= 0) {
969
				$pipeno = captiveportal_get_dn_passthru_ruleno($emac['mac']);
970
				if ($pipeno) {
971
					captiveportal_free_dn_ruleno($pipeno);
972
					$macrules .= "table {$cpzone}_pipe_mac delete any,{$emac['mac']}\n";
973
					$macrules .= "table {$cpzone}_pipe_mac delete {$emac['mac']},any\n";
974
					$macrules .= "pipe delete {$pipeno}\n";
975
					++$pipeno;
976
					$macrules .= "pipe delete {$pipeno}\n";
977
				}
978
				$writecfg = true;
979
				captiveportal_logportalauth($emac['username'], $emac['mac'],
980
				    $emac['ip'], "EXPIRED {$emac['username']} LOGIN - TERMINATING SESSION");
981
				unset($config['captiveportal'][$cpzone]['passthrumac'][$eid]);
982
			}
983
		}
984
		unset($tmpvoucherdb);
985
		if (!empty($macrules)) {
986
			@file_put_contents("{$g['tmp_path']}/macentry.prunerules.tmp", $macrules);
987
			unset($macrules);
988
			mwexec("/sbin/ipfw -q {$g['tmp_path']}/macentry.prunerules.tmp");
989
		}
990
		if ($writecfg === true) {
991
			write_config("Prune session for auto-added macs");
992
		}
993
	}
994
}
995

    
996
/* remove a single client according to the DB entry */
997
function captiveportal_disconnect($dbent, $radiusservers, $term_cause = 1,
998
    $stop_time = null) {
999
	global $g, $config, $cpzone, $cpzoneid;
1000

    
1001
	$stop_time = (empty($stop_time)) ? time() : $stop_time;
1002

    
1003
	/* this client needs to be deleted - remove ipfw rules */
1004
	if (isset($config['captiveportal'][$cpzone]['radacct_enable']) &&
1005
	    !empty($radiusservers)) {
1006
		if ($config['captiveportal'][$cpzone]['reauthenticateacct'] ==
1007
		    "stopstartfreeradius") {
1008
			/*
1009
			 * Interim updates are on so the session time must be
1010
			 * reported as the elapsed time since the previous
1011
			 * interim update.
1012
			 */
1013
			$session_time = ($stop_time - $dbent[0]) % 60;
1014
			$start_time = $stop_time - $session_time;
1015
		} else {
1016
			$start_time = $dbent[0];
1017
		}
1018
		RADIUS_ACCOUNTING_STOP($dbent[1], // ruleno
1019
			$dbent[4], // username
1020
			$dbent[5], // sessionid
1021
			$start_time, // start time
1022
			$radiusservers,
1023
			$dbent[2], // clientip
1024
			$dbent[3], // clientmac
1025
			$term_cause, // Acct-Terminate-Cause
1026
			false,
1027
			$stop_time);
1028
	}
1029

    
1030
	if (is_ipaddr($dbent[2])) {
1031
		/*
1032
		 * Delete client's ip entry from tables auth_up and auth_down.
1033
		 * It's not necessary to explicit specify mac address here
1034
		 */
1035
		$cpsession = captiveportal_isip_logged($dbent[2]);
1036
		if (!empty($cpsession)) {
1037
			$clientsn = (is_ipaddrv6($dbent[2])) ? 128 : 32;
1038
			pfSense_ipfw_table("{$cpzone}_auth_up",
1039
			    IP_FW_TABLE_XDEL, "{$dbent[2]}/{$clientsn}");
1040
			pfSense_ipfw_table("{$cpzone}_auth_down",
1041
			    IP_FW_TABLE_XDEL, "{$dbent[2]}/{$clientsn}");
1042
		}
1043
		/* XXX: Redundant?! Ensure all pf(4) states are killed. */
1044
		$_gb = @pfSense_kill_states($dbent[2]);
1045
		$_gb = @pfSense_kill_srcstates($dbent[2]);
1046
	}
1047

    
1048
	/*
1049
	 * These are the pipe numbers we use to control traffic shaping for
1050
	 * each logged in user via captive portal
1051
	 * We could get an error if the pipe doesn't exist but everything
1052
	 * should still be fine
1053
	 */
1054
	if (!empty($dbent[1])) {
1055
		/*
1056
		 * Call captiveportal_free_dnrules() in dry_run mode to verify
1057
		 * if there are pipes to be removed and prevent the attempt to
1058
		 * delete invalid pipes
1059
		 */
1060
		$removed_pipes = captiveportal_free_dnrules($dbent[1],
1061
		    $dbent[1]+1, true);
1062

    
1063
		if (!empty($removed_pipes)) {
1064
			$_gb = @pfSense_ipfw_pipe("pipe delete {$dbent[1]}");
1065
			$_gb = @pfSense_ipfw_pipe("pipe delete " .
1066
			    ($dbent[1]+1));
1067

    
1068
			/*
1069
			 * Release the ruleno so it can be reallocated to new
1070
			 * clients
1071
			 */
1072
			captiveportal_free_dn_ruleno($dbent[1]);
1073
		}
1074
	}
1075

    
1076
	// XMLRPC Call over to the master Voucher node
1077
	if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) {
1078
		$syncip   = $config['voucher'][$cpzone]['vouchersyncdbip'];
1079
		$syncport = $config['voucher'][$cpzone]['vouchersyncport'];
1080
		$syncpass = $config['voucher'][$cpzone]['vouchersyncpass'];
1081
		$vouchersyncusername =
1082
		    $config['voucher'][$cpzone]['vouchersyncusername'];
1083
		$remote_status = xmlrpc_sync_voucher_disconnect($dbent, $syncip,
1084
		    $syncport, $syncpass, $vouchersyncusername, $term_cause,
1085
		    $stop_time);
1086
	}
1087

    
1088
}
1089

    
1090
/* remove a single client by sessionid */
1091
function captiveportal_disconnect_client($sessionid, $term_cause = 1, $logoutReason = "LOGOUT") {
1092
	global $g, $config;
1093

    
1094
	$sessionid = SQLite3::escapeString($sessionid);
1095
	$radiusservers = captiveportal_get_radius_servers();
1096

    
1097
	/* read database */
1098
	$result = captiveportal_read_db("WHERE sessionid = '{$sessionid}'");
1099

    
1100
	/* find entry */
1101
	if (!empty($result)) {
1102
		captiveportal_write_db("DELETE FROM captiveportal WHERE sessionid = '{$sessionid}'");
1103

    
1104
		foreach ($result as $cpentry) {
1105
			if (empty($cpentry[11])) {
1106
				$cpentry[11] = 'first';
1107
			}
1108
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], $term_cause);
1109
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "DISCONNECT");
1110
		}
1111
		unset($result);
1112
	}
1113
}
1114

    
1115
/* remove all clients */
1116
function captiveportal_disconnect_all($term_cause = 6, $logoutReason = "DISCONNECT") {
1117
	global $g, $config, $cpzone, $cpzoneid;
1118

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

    
1122
	/* if we still don't have the lock, unlock forcefully and take it */
1123
	if (!$rcprunelock) {
1124
		log_error("CP zone ${cpzone}: could not obtain the lock for more than 15 seconds, lock taken forcefully to disconnect all users");
1125
		unlock_force("rcprunecaptiveportal{$cpzone}");
1126
		$rcprunelock = lock("rcprunecaptiveportal{$cpzone}", LOCK_EX);
1127
	}
1128

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

    
1132
	captiveportal_radius_stop_all($term_cause, $logoutReason);
1133

    
1134
	/* remove users from the database */
1135
	$cpdb = captiveportal_read_db();
1136
	$unsetindexes = array_column($cpdb,5);
1137
	if (!empty($unsetindexes)) {
1138
		captiveportal_remove_entries($unsetindexes);
1139
	}
1140

    
1141
	/* reinit ipfw rules */
1142
	captiveportal_init_rules(true);
1143

    
1144
	unlock($cpdblck);
1145
	unlock($rcprunelock);
1146
}
1147

    
1148
/* send RADIUS acct stop for all current clients */
1149
function captiveportal_radius_stop_all($term_cause = 6, $logoutReason = "DISCONNECT") {
1150
	global $g, $config, $cpzone, $cpzoneid;
1151

    
1152
	$cpdb = captiveportal_read_db();
1153

    
1154
	$radacct = isset($config['captiveportal'][$cpzone]['radacct_enable']) ? true : false;
1155
	if ($radacct) {
1156
		$radiusservers = captiveportal_get_radius_servers();
1157
	}
1158

    
1159
	foreach ($cpdb as $cpentry) {
1160
		if ($radacct) {
1161
			if (!empty($radiusservers)) {
1162
				if (empty($cpentry[11])) {
1163
					$cpentry[11] = 'first';
1164
				}
1165
				if (!empty($radiusservers[$cpentry[11]])) {
1166
					RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
1167
						$cpentry[4], // username
1168
						$cpentry[5], // sessionid
1169
						$cpentry[0], // start time
1170
						$radiusservers[$cpentry[11]],
1171
						$cpentry[2], // clientip
1172
						$cpentry[3], // clientmac
1173
						$term_cause);
1174
				}
1175
			}
1176
		}
1177
		captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], $logoutReason);
1178
	}
1179
	unset($cpdb);
1180
}
1181

    
1182
function captiveportal_passthrumac_configure_entry($macent, $pipeinrule = false) {
1183
	global $config, $g, $cpzone;
1184

    
1185
	$bwUp = 0;
1186
	if (!empty($macent['bw_up'])) {
1187
		$bwUp = $macent['bw_up'];
1188
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1189
		$bwUp = $config['captiveportal'][$cpzone]['bwdefaultup'];
1190
	}
1191
	$bwDown = 0;
1192
	if (!empty($macent['bw_down'])) {
1193
		$bwDown = $macent['bw_down'];
1194
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1195
		$bwDown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1196
	}
1197

    
1198
	if ($macent['action'] == 'pass') {
1199
		$rules = "";
1200

    
1201
		$pipeno = captiveportal_get_next_dn_ruleno();
1202

    
1203
		$pipeup = $pipeno;
1204
		if ($pipeinrule == true) {
1205
			$_gb = @pfSense_ipfw_pipe("pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16");
1206
		} else {
1207
			$rules .= "pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16\n";
1208
		}
1209

    
1210
		$pipedown = $pipeno + 1;
1211
		if ($pipeinrule == true) {
1212
			$_gb = @pfSense_ipfw_pipe("pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16");
1213
		} else {
1214
			$rules .= "pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16\n";
1215
		}
1216

    
1217
		$rules .= "table {$cpzone}_pipe_mac add any,{$macent['mac']} {$pipeup}\n";
1218
		$rules .= "table {$cpzone}_pipe_mac add {$macent['mac']},any {$pipedown}\n";
1219
	}
1220

    
1221
	return $rules;
1222
}
1223

    
1224
function captiveportal_passthrumac_delete_entry($macent) {
1225
	global $cpzone;
1226
	$rules = "";
1227

    
1228
	if ($macent['action'] == 'pass') {
1229
		$pipeno = captiveportal_get_dn_passthru_ruleno($macent['mac']);
1230

    
1231
		if (!empty($pipeno)) {
1232
			captiveportal_free_dn_ruleno($pipeno);
1233
			$rules .= "table {$cpzone}_pipe_mac delete any,{$macent['mac']}\n";
1234
			$rules .= "table {$cpzone}_pipe_mac delete {$macent['mac']},any\n";
1235
			$rules .= "pipe delete " . $pipeno . "\n";
1236
			$rules .= "pipe delete " . ++$pipeno . "\n";
1237
		}
1238
	}
1239

    
1240
	return $rules;
1241
}
1242

    
1243
function captiveportal_passthrumac_configure($filename = false, $startindex = 0, $stopindex = 0) {
1244
	global $config, $g, $cpzone;
1245

    
1246
	$rules = "";
1247

    
1248
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1249
		if ($stopindex > 0) {
1250
			$fd = fopen($filename, "w");
1251
			for ($idx = $startindex; $idx <= $stopindex; $idx++) {
1252
				if (isset($config['captiveportal'][$cpzone]['passthrumac'][$idx])) {
1253
					$rules = captiveportal_passthrumac_configure_entry($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
1254
					fwrite($fd, $rules);
1255
				}
1256
			}
1257
			fclose($fd);
1258

    
1259
			return;
1260
		} else {
1261
			$nentries = count($config['captiveportal'][$cpzone]['passthrumac']);
1262
			if ($nentries > 2000) {
1263
				$nloops = $nentries / 1000;
1264
				$remainder= $nentries % 1000;
1265
				for ($i = 0; $i < $nloops; $i++) {
1266
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . ((($i+1) * 1000) - 1) . "\"");
1267
				}
1268
				if ($remainder > 0) {
1269
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . (($i* 1000) + $remainder) ."\"");
1270
				}
1271
			} else {
1272
				foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1273
					$rules .= captiveportal_passthrumac_configure_entry($macent, true);
1274
				}
1275
			}
1276
		}
1277
	}
1278

    
1279
	return $rules;
1280
}
1281

    
1282
function captiveportal_passthrumac_findbyname($username) {
1283
	global $config, $cpzone;
1284

    
1285
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1286
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1287
			if ($macent['username'] == $username) {
1288
				return $macent;
1289
			}
1290
		}
1291
	}
1292
	return NULL;
1293
}
1294

    
1295
/*
1296
 * table (3=IN)/(4=OUT) hold allowed ip's without bw limits
1297
 */
1298
function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) {
1299
	global $g, $config, $cpzone;
1300

    
1301
	/*  Instead of copying this entire function for something
1302
	 *  easy such as hostname vs ip address add this check
1303
	 */
1304
	if ($ishostname === true) {
1305
		if (!platform_booting()) {
1306
			$ipaddress = gethostbyname($ipent['hostname']);
1307
			if (!is_ipaddr($ipaddress)) {
1308
				return;
1309
			}
1310
		} else {
1311
			$ipaddress = "";
1312
		}
1313
	} else {
1314
		$ipaddress = $ipent['ip'];
1315
	}
1316

    
1317
	$rules = "";
1318
	$cp_filterdns_conf = "";
1319
	$enBwup = 0;
1320
	if (!empty($ipent['bw_up'])) {
1321
		$enBwup = intval($ipent['bw_up']);
1322
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1323
		$enBwup = $config['captiveportal'][$cpzone]['bwdefaultup'];
1324
	}
1325
	$enBwdown = 0;
1326
	if (!empty($ipent['bw_down'])) {
1327
		$enBwdown = intval($ipent['bw_down']);
1328
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1329
		$enBwdown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1330
	}
1331

    
1332
	$pipeup = captiveportal_get_next_dn_ruleno();
1333
	$_gb = @pfSense_ipfw_pipe("pipe {$pipeup} config bw {$enBwup}Kbit/s queue 100 buckets 16");
1334
	$pipedown = $pipeup + 1;
1335
	$_gb = @pfSense_ipfw_pipe("pipe {$pipedown} config bw {$enBwdown}Kbit/s queue 100 buckets 16");
1336

    
1337
	if ($ishostname === true) {
1338
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} {$cpzone}_allowed_up pipe {$pipeup}\n";
1339
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} {$cpzone}_allowed_down pipe {$pipedown}\n";
1340
		if (!is_ipaddr($ipaddress)) {
1341
			return array("", $cp_filterdns_conf);
1342
		}
1343
	}
1344

    
1345
	$subnet = "";
1346
	if (!empty($ipent['sn'])) {
1347
		$subnet = "/{$ipent['sn']}";
1348
	}
1349
	$rules .= "table {$cpzone}_allowed_up add {$ipaddress}{$subnet} {$pipeup}\n";
1350
	$rules .= "table {$cpzone}_allowed_down add {$ipaddress}{$subnet} {$pipedown}\n";
1351

    
1352
	if ($ishostname === true) {
1353
		return array($rules, $cp_filterdns_conf);
1354
	} else {
1355
		return $rules;
1356
	}
1357
}
1358

    
1359
function captiveportal_allowedhostname_configure() {
1360
	global $config, $g, $cpzone, $cpzoneid;
1361

    
1362
	$rules = "";
1363
	if (!is_array($config['captiveportal'][$cpzone]['allowedhostname'])) {
1364
		return $rules;
1365
	}
1366

    
1367
	$rules = "\n# captiveportal_allowedhostname_configure()\n";
1368
	$cp_filterdns_conf = "";
1369
	foreach ($config['captiveportal'][$cpzone]['allowedhostname'] as $hostnameent) {
1370
		$tmprules = captiveportal_allowedip_configure_entry($hostnameent, true);
1371
		$rules .= $tmprules[0];
1372
		$cp_filterdns_conf .= $tmprules[1];
1373
	}
1374
	$cp_filterdns_filename = "{$g['varetc_path']}/filterdns-{$cpzone}-captiveportal.conf";
1375
	@file_put_contents($cp_filterdns_filename, $cp_filterdns_conf);
1376
	unset($cp_filterdns_conf);
1377

    
1378
	return $rules;
1379
}
1380

    
1381
function captiveportal_filterdns_configure() {
1382
	global $config, $g, $cpzone, $cpzoneid;
1383

    
1384
	$cp_filterdns_filename = $g['varetc_path'] .
1385
	    "/filterdns-{$cpzone}-captiveportal.conf";
1386

    
1387
	if (isset($config['captiveportal'][$cpzone]['enable']) &&
1388
	    is_array($config['captiveportal'][$cpzone]['allowedhostname']) &&
1389
	    file_exists($cp_filterdns_filename)) {
1390
		if (isvalidpid($g['varrun_path'] .
1391
		    "/filterdns-{$cpzone}-cpah.pid")) {
1392
			sigkillbypid($g['varrun_path'] .
1393
			    "/filterdns-{$cpzone}-cpah.pid", "HUP");
1394
		} else {
1395
			mwexec("/usr/local/sbin/filterdns -p " .
1396
			    "{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid" .
1397
			    " -i 300 -c {$cp_filterdns_filename} -d 1");
1398
		}
1399
	} else {
1400
		killbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1401
		@unlink("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1402
	}
1403

    
1404
	return $rules;
1405
}
1406

    
1407
function captiveportal_allowedip_configure() {
1408
	global $config, $g, $cpzone;
1409

    
1410
	$rules = "";
1411
	if (is_array($config['captiveportal'][$cpzone]['allowedip'])) {
1412
		foreach ($config['captiveportal'][$cpzone]['allowedip'] as $ipent) {
1413
			$rules .= captiveportal_allowedip_configure_entry($ipent);
1414
		}
1415
	}
1416

    
1417
	return $rules;
1418
}
1419

    
1420
/* get last activity timestamp given client IP address */
1421
function captiveportal_get_last_activity($ip) {
1422
	global $cpzone;
1423

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

    
1427
	foreach ($tables as $table) {
1428
		$ipfw = pfSense_ipfw_table_lookup($table, $ip);
1429
		if (is_array($ipfw)) {
1430
			/* Workaround for #46652 */
1431
			if ($ipfw['packets'] > 0) {
1432
				return $ipfw['timestamp'];
1433
			} else {
1434
				return 0;
1435
			}
1436
		}
1437
	}
1438

    
1439
	return 0;
1440
}
1441

    
1442
function captiveportal_init_radius_servers() {
1443
	global $config, $g, $cpzone;
1444

    
1445
	/* generate radius server database */
1446
	if ($config['captiveportal'][$cpzone]['radiusip'] &&
1447
	    (!isset($config['captiveportal'][$cpzone]['auth_method']) || $config['captiveportal'][$cpzone]['auth_method'] == "radius")) {
1448
		$radiusip = $config['captiveportal'][$cpzone]['radiusip'];
1449
		$radiusip2 = ($config['captiveportal'][$cpzone]['radiusip2']) ? $config['captiveportal'][$cpzone]['radiusip2'] : null;
1450
		$radiusip3 = ($config['captiveportal'][$cpzone]['radiusip3']) ? $config['captiveportal'][$cpzone]['radiusip3'] : null;
1451
		$radiusip4 = ($config['captiveportal'][$cpzone]['radiusip4']) ? $config['captiveportal'][$cpzone]['radiusip4'] : null;
1452

    
1453
		if ($config['captiveportal'][$cpzone]['radiusport']) {
1454
			$radiusport = $config['captiveportal'][$cpzone]['radiusport'];
1455
		} else {
1456
			$radiusport = 1812;
1457
		}
1458
		if ($config['captiveportal'][$cpzone]['radiusacctport']) {
1459
			$radiusacctport = $config['captiveportal'][$cpzone]['radiusacctport'];
1460
		} else {
1461
			$radiusacctport = 1813;
1462
		}
1463
		if ($config['captiveportal'][$cpzone]['radiusport2']) {
1464
			$radiusport2 = $config['captiveportal'][$cpzone]['radiusport2'];
1465
		} else {
1466
			$radiusport2 = 1812;
1467
		}
1468
		if ($config['captiveportal'][$cpzone]['radiusport3']) {
1469
			$radiusport3 = $config['captiveportal'][$cpzone]['radiusport3'];
1470
		} else {
1471
			$radiusport3 = 1812;
1472
		}
1473
		if ($config['captiveportal'][$cpzone]['radiusport4']) {
1474
			$radiusport4 = $config['captiveportal'][$cpzone]['radiusport4'];
1475
		} else {
1476
			$radiusport4 = 1812;
1477
		}
1478

    
1479
		$radiuskey = $config['captiveportal'][$cpzone]['radiuskey'];
1480
		$radiuskey2 = $config['captiveportal'][$cpzone]['radiuskey2'];
1481
		$radiuskey3 = $config['captiveportal'][$cpzone]['radiuskey3'];
1482
		$radiuskey4 = $config['captiveportal'][$cpzone]['radiuskey4'];
1483

    
1484
		$cprdsrvlck = lock("captiveportalradius{$cpzone}", LOCK_EX);
1485
		$fd = @fopen("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db", "w");
1486
		if (!$fd) {
1487
			captiveportal_syslog("Error: cannot open RADIUS DB file in captiveportal_configure().\n");
1488
			unlock($cprdsrvlck);
1489
			return 1;
1490
		}
1491
		if (isset($radiusip)) {
1492
			fwrite($fd, $radiusip . "," . $radiusport . "," . $radiusacctport . "," . $radiuskey . ",first");
1493
		}
1494
		if (isset($radiusip2)) {
1495
			fwrite($fd, "\n" . $radiusip2 . "," . $radiusport2 . "," . $radiusacctport . "," . $radiuskey2 . ",first");
1496
		}
1497
		if (isset($radiusip3)) {
1498
			fwrite($fd, "\n" . $radiusip3 . "," . $radiusport3 . "," . $radiusacctport . "," . $radiuskey3 . ",second");
1499
		}
1500
		if (isset($radiusip4)) {
1501
			fwrite($fd, "\n" . $radiusip4 . "," . $radiusport4 . "," . $radiusacctport . "," . $radiuskey4 . ",second");
1502
		}
1503

    
1504
		fclose($fd);
1505
		unlock($cprdsrvlck);
1506
	}
1507
}
1508

    
1509
/* read RADIUS servers into array */
1510
function captiveportal_get_radius_servers() {
1511
	global $g, $cpzone;
1512

    
1513
	$cprdsrvlck = lock("captiveportalradius{$cpzone}");
1514
	if (file_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db")) {
1515
		$radiusservers = array();
1516
		$cpradiusdb = file("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db",
1517
		FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1518
		if ($cpradiusdb) {
1519
			foreach ($cpradiusdb as $cpradiusentry) {
1520
				$line = trim($cpradiusentry);
1521
				if ($line) {
1522
					$radsrv = array();
1523
					list($radsrv['ipaddr'], $radsrv['port'], $radsrv['acctport'], $radsrv['key'], $context) = explode(",", $line);
1524
				}
1525
				if (empty($context)) {
1526
					if (!is_array($radiusservers['first'])) {
1527
						$radiusservers['first'] = array();
1528
					}
1529
					$radiusservers['first'] = $radsrv;
1530
				} else {
1531
					if (!is_array($radiusservers[$context])) {
1532
						$radiusservers[$context] = array();
1533
					}
1534
					$radiusservers[$context][] = $radsrv;
1535
				}
1536
			}
1537
		}
1538
		unlock($cprdsrvlck);
1539
		return $radiusservers;
1540
	}
1541

    
1542
	unlock($cprdsrvlck);
1543
	return false;
1544
}
1545

    
1546
/* log successful captive portal authentication to syslog */
1547
/* part of this code from php.net */
1548
function captiveportal_logportalauth($user, $mac, $ip, $status, $message = null) {
1549
	// Log it
1550
	if (!$message) {
1551
		$message = "{$status}: {$user}, {$mac}, {$ip}";
1552
	} else {
1553
		$message = trim($message);
1554
		$message = "{$status}: {$user}, {$mac}, {$ip}, {$message}";
1555
	}
1556
	captiveportal_syslog($message);
1557
}
1558

    
1559
/* log simple messages to syslog */
1560
function captiveportal_syslog($message) {
1561
	global $cpzone;
1562

    
1563
	$message = trim($message);
1564
	$message = "Zone: {$cpzone} - {$message}";
1565
	openlog("logportalauth", LOG_PID, LOG_LOCAL4);
1566
	// Log it
1567
	syslog(LOG_INFO, $message);
1568
	closelog();
1569
}
1570

    
1571
function radius($username, $password, $clientip, $clientmac, $type, $radiusctx = null) {
1572
	global $g, $config, $cpzoneid;
1573

    
1574
	$pipeno = captiveportal_get_next_dn_ruleno();
1575

    
1576
	/* If the pool is empty, return appropriate message and fail authentication */
1577
	if (empty($pipeno)) {
1578
		$auth_list = array();
1579
		$auth_list['auth_val'] = 1;
1580
		$auth_list['error'] = "System reached maximum login capacity";
1581
		return $auth_list;
1582
	}
1583

    
1584
	$radiusservers = captiveportal_get_radius_servers();
1585

    
1586
	if (is_null($radiusctx)) {
1587
		$radiusctx = 'first';
1588
	}
1589

    
1590
	$auth_list = RADIUS_AUTHENTICATION($username,
1591
		$password,
1592
		$radiusservers[$radiusctx],
1593
		$clientip,
1594
		$clientmac,
1595
		$pipeno);
1596

    
1597
	if ($auth_list['auth_val'] == 2) {
1598
		captiveportal_logportalauth($username, $clientmac, $clientip, $type);
1599
		$sessionid = portal_allow($clientip,
1600
			$clientmac,
1601
			$username,
1602
			$password,
1603
			$auth_list,
1604
			$pipeno,
1605
			$radiusctx);
1606
	} else {
1607
		captiveportal_free_dn_ruleno($pipeno);
1608
	}
1609

    
1610
	return $auth_list;
1611
}
1612

    
1613
function captiveportal_opendb() {
1614
	global $g, $config, $cpzone, $cpzoneid;
1615

    
1616
	$db_path = "{$g['vardb_path']}/captiveportal{$cpzone}.db";
1617
	$createquery = "CREATE TABLE IF NOT EXISTS captiveportal (" .
1618
				"allow_time INTEGER, pipeno INTEGER, ip TEXT, mac TEXT, username TEXT, " .
1619
				"sessionid TEXT, bpassword TEXT, session_timeout INTEGER, idle_timeout INTEGER, " .
1620
				"session_terminate_time INTEGER, interim_interval INTEGER, radiusctx TEXT); " .
1621
			"CREATE UNIQUE INDEX IF NOT EXISTS idx_active ON captiveportal (sessionid, username); " .
1622
			"CREATE INDEX IF NOT EXISTS user ON captiveportal (username); " .
1623
			"CREATE INDEX IF NOT EXISTS ip ON captiveportal (ip); " .
1624
			"CREATE INDEX IF NOT EXISTS starttime ON captiveportal (allow_time)";
1625

    
1626
	try {
1627
		$DB = new SQLite3($db_path);
1628
		$DB->busyTimeout(60000);
1629
	} catch (Exception $e) {
1630
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: " . $e->getMessage() . " -- Trying again.");
1631
		unlink_if_exists($db_path);
1632
		try {
1633
			$DB = new SQLite3($db_path);
1634
			$DB->busyTimeout(60000);
1635
		} catch (Exception $e) {
1636
			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.");
1637
			return;
1638
		}
1639
	}
1640

    
1641
	if (!$DB) {
1642
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Trying again.");
1643
		unlink_if_exists($db_path);
1644
		$DB = new SQLite3($db_path);
1645
		$DB->busyTimeout(60000);
1646
		if (!$DB) {
1647
			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.");
1648
			return;
1649
		}
1650
	}
1651

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

    
1655
		/* If unable to initialize the database, reset and try again. */
1656
		$DB->close();
1657
		unset($DB);
1658
		unlink_if_exists($db_path);
1659
		$DB = new SQLite3($db_path);
1660
		$DB->busyTimeout(60000);
1661
		if ($DB->exec($createquery)) {
1662
			captiveportal_syslog("Successfully reinitialized tables for {$cpzone} -- database has been reset.");
1663
			if (!is_numericint($cpzoneid)) {
1664
				if (is_array($config['captiveportal'])) {
1665
					foreach ($config['captiveportal'] as $cpkey => $cp) {
1666
						if ($cpzone == $cpkey) {
1667
							$cpzoneid = $cp['zoneid'];
1668
						}
1669
					}
1670
				}
1671
			}
1672
			if (is_numericint($cpzoneid)) {
1673
				$table_names = captiveportal_get_ipfw_table_names();
1674
				foreach ($table_names as $table_name) {
1675
					mwexec("/sbin/ipfw table {$table_name} flush");
1676
				}
1677
				captiveportal_syslog("Flushed tables for {$cpzone} after database reset.");
1678
			}
1679
		} else {
1680
			captiveportal_syslog("Still unable to create tables for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Remove the database file manually and try again.");
1681
		}
1682
	}
1683

    
1684
	return $DB;
1685
}
1686

    
1687
/* Get all tables for specific cpzone */
1688
function captiveportal_get_ipfw_table_names() {
1689
	global $cpzone;
1690

    
1691
	$result = array();
1692
	$tables = pfSense_ipfw_tables_list();
1693

    
1694
	if (!is_array($tables)) {
1695
		return $result;
1696
	}
1697

    
1698
	$len = strlen($cpzone) + 1;
1699
	foreach ($tables as $table) {
1700
		if (substr($table['name'], 0, $len) != $cpzone . '_') {
1701
			continue;
1702
		}
1703

    
1704
		$result[] = $table['name'];
1705
	}
1706

    
1707
	return $result;
1708
}
1709

    
1710
/* read captive portal DB into array */
1711
function captiveportal_read_db($query = "") {
1712
	$cpdb = array();
1713

    
1714
	$DB = captiveportal_opendb();
1715
	if ($DB) {
1716
		$response = $DB->query("SELECT * FROM captiveportal {$query}");
1717
		if ($response != FALSE) {
1718
			while ($row = $response->fetchArray()) {
1719
				$cpdb[] = $row;
1720
			}
1721
		}
1722
		$DB->close();
1723
	}
1724

    
1725
	return $cpdb;
1726
}
1727

    
1728
function captiveportal_remove_entries($remove) {
1729

    
1730
	if (!is_array($remove) || empty($remove)) {
1731
		return;
1732
	}
1733

    
1734
	$query = "DELETE FROM captiveportal WHERE sessionid in (";
1735
	foreach ($remove as $idx => $unindex) {
1736
		$query .= "'{$unindex}'";
1737
		if ($idx < (count($remove) - 1)) {
1738
			$query .= ",";
1739
		}
1740
	}
1741
	$query .= ")";
1742
	captiveportal_write_db($query);
1743
}
1744

    
1745
/* write captive portal DB */
1746
function captiveportal_write_db($queries) {
1747
	global $g;
1748

    
1749
	if (is_array($queries)) {
1750
		$query = implode(";", $queries);
1751
	} else {
1752
		$query = $queries;
1753
	}
1754

    
1755
	$DB = captiveportal_opendb();
1756
	if ($DB) {
1757
		$DB->exec("BEGIN TRANSACTION");
1758
		$result = $DB->exec($query);
1759
		if (!$result) {
1760
			captiveportal_syslog("Trying to modify DB returned error: {$DB->lastErrorMsg()}");
1761
		} else {
1762
			$DB->exec("END TRANSACTION");
1763
		}
1764
		$DB->close();
1765
		return $result;
1766
	} else {
1767
		return true;
1768
	}
1769
}
1770

    
1771
function captiveportal_write_elements() {
1772
	global $g, $config, $cpzone;
1773

    
1774
	$cpcfg = $config['captiveportal'][$cpzone];
1775

    
1776
	if (!is_dir($g['captiveportal_element_path'])) {
1777
		@mkdir($g['captiveportal_element_path']);
1778
	}
1779

    
1780
	if (is_array($cpcfg['element'])) {
1781
		foreach ($cpcfg['element'] as $data) {
1782
			/* Do not attempt to decode or write out empty files. */
1783
			if (empty($data['content']) || empty(base64_decode($data['content']))) {
1784
				unlink_if_exists("{$g['captiveportal_element_path']}/{$data['name']}");
1785
				touch("{$g['captiveportal_element_path']}/{$data['name']}");
1786
			} elseif (!@file_put_contents("{$g['captiveportal_element_path']}/{$data['name']}", base64_decode($data['content']))) {
1787
				printf(gettext('Error: cannot open \'%1$s\' in captiveportal_write_elements()%2$s'), $data['name'], "\n");
1788
				return 1;
1789
			}
1790
			if (!file_exists("{$g['captiveportal_path']}/{$data['name']}")) {
1791
				@symlink("{$g['captiveportal_element_path']}/{$data['name']}", "{$g['captiveportal_path']}/{$data['name']}");
1792
			}
1793
		}
1794
	}
1795

    
1796
	return 0;
1797
}
1798

    
1799
function captiveportal_free_dnrules($rulenos_start = 2000,
1800
    $rulenos_range_max = 64500, $dry_run = false) {
1801
	global $g, $cpzone;
1802

    
1803
	$removed_pipes = array();
1804

    
1805
	if (!file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1806
		return $removed_pipes;
1807
	}
1808

    
1809
	if (!$dry_run) {
1810
		$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1811
	}
1812

    
1813
	$rules = unserialize(file_get_contents(
1814
	    "{$g['vardb_path']}/captiveportaldn.rules"));
1815
	$ridx = $rulenos_start;
1816
	while ($ridx < $rulenos_range_max) {
1817
		if ($rules[$ridx] == $cpzone) {
1818
			if (!$dry_run) {
1819
				$rules[$ridx] = false;
1820
			}
1821
			$removed_pipes[] = $ridx;
1822
			$ridx++;
1823
			if (!$dry_run) {
1824
				$rules[$ridx] = false;
1825
			}
1826
			$removed_pipes[] = $ridx;
1827
			$ridx++;
1828
		} else {
1829
			$ridx += 2;
1830
		}
1831
	}
1832

    
1833
	if (!$dry_run) {
1834
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules",
1835
		    serialize($rules));
1836
		unlock($cpruleslck);
1837
	}
1838

    
1839
	unset($rules);
1840

    
1841
	return $removed_pipes;
1842
}
1843

    
1844
function captiveportal_get_next_dn_ruleno($rulenos_start = 2000, $rulenos_range_max = 64500) {
1845
	global $config, $g, $cpzone;
1846

    
1847
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1848
	$ruleno = 0;
1849
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1850
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1851
		$ridx = $rulenos_start;
1852
		while ($ridx < $rulenos_range_max) {
1853
			if (empty($rules[$ridx])) {
1854
				$ruleno = $ridx;
1855
				$rules[$ridx] = $cpzone;
1856
				$ridx++;
1857
				$rules[$ridx] = $cpzone;
1858
				break;
1859
			} else {
1860
				$ridx += 2;
1861
			}
1862
		}
1863
	} else {
1864
		$rules = array_pad(array(), $rulenos_range_max, false);
1865
		$ruleno = $rulenos_start;
1866
		$rules[$rulenos_start] = $cpzone;
1867
		$rulenos_start++;
1868
		$rules[$rulenos_start] = $cpzone;
1869
	}
1870
	file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1871
	unlock($cpruleslck);
1872
	unset($rules);
1873

    
1874
	return $ruleno;
1875
}
1876

    
1877
function captiveportal_free_dn_ruleno($ruleno) {
1878
	global $config, $g;
1879

    
1880
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1881
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1882
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1883
		$rules[$ruleno] = false;
1884
		$ruleno++;
1885
		$rules[$ruleno] = false;
1886
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1887
		unset($rules);
1888
	}
1889
	unlock($cpruleslck);
1890
}
1891

    
1892
function captiveportal_get_dn_passthru_ruleno($value) {
1893
	global $config, $g, $cpzone, $cpzoneid;
1894

    
1895
	$cpcfg = $config['captiveportal'][$cpzone];
1896
	if (!isset($cpcfg['enable'])) {
1897
		return NULL;
1898
	}
1899

    
1900
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1901
	$ruleno = NULL;
1902
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1903
		unset($output);
1904
		$item = pfSense_ipfw_table_lookup("{$cpzone}_pipe_mac",
1905
		    "any,{$value}");
1906
		if (!is_array($item) || empty($item['pipe'])) {
1907
			unlock($cpruleslck);
1908
			return NULL;
1909
		}
1910

    
1911
		$ruleno = intval($item['pipe']);
1912
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1913
		if (!$rules[$ruleno]) {
1914
			$ruleno = NULL;
1915
		}
1916
		unset($rules);
1917
	}
1918
	unlock($cpruleslck);
1919

    
1920
	return $ruleno;
1921
}
1922

    
1923
/**
1924
 * This function will calculate the traffic produced by a client
1925
 * based on its firewall rule
1926
 *
1927
 * Point of view: NAS
1928
 *
1929
 * Input means: from the client
1930
 * Output means: to the client
1931
 *
1932
 */
1933

    
1934
function getVolume($ip) {
1935
	global $config, $cpzone;
1936

    
1937
	$reverse = isset($config['captiveportal'][$cpzone]['reverseacct'])
1938
	    ? true : false;
1939
	$volume = array();
1940
	// Initialize vars properly, since we don't want NULL vars
1941
	$volume['input_pkts'] = $volume['input_bytes'] = 0;
1942
	$volume['output_pkts'] = $volume['output_bytes'] = 0;
1943

    
1944
	$tables = array("allowed", "auth");
1945

    
1946
	foreach($tables as $table) {
1947
		$ipfw = pfSense_ipfw_table_lookup("{$cpzone}_{$table}_up", $ip);
1948
		if (!is_array($ipfw)) {
1949
			continue;
1950
		}
1951
		if ($reverse) {
1952
			$volume['output_pkts'] = $ipfw['packets'];
1953
			$volume['output_bytes'] = $ipfw['bytes'];
1954
		} else {
1955
			$volume['input_pkts'] = $ipfw['packets'];
1956
			$volume['input_bytes'] = $ipfw['bytes'];
1957
		}
1958
	}
1959

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

    
1975
	return $volume;
1976
}
1977

    
1978
/**
1979
 * Get the NAS-IP-Address based on the current wan address
1980
 *
1981
 * Use functions in interfaces.inc to find this out
1982
 *
1983
 */
1984

    
1985
function getNasIP() {
1986
	global $config, $cpzone;
1987

    
1988
	if (empty($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1989
			$nasIp = get_interface_ip();
1990
	} else {
1991
		if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1992
			$nasIp = $config['captiveportal'][$cpzone]['radiussrcip_attribute'];
1993
		} else {
1994
			$nasIp = get_interface_ip($config['captiveportal'][$cpzone]['radiussrcip_attribute']);
1995
		}
1996
	}
1997

    
1998
	if (!is_ipaddr($nasIp)) {
1999
		$nasIp = "0.0.0.0";
2000
	}
2001

    
2002
	return $nasIp;
2003
}
2004

    
2005
function portal_ip_from_client_ip($cliip) {
2006
	global $config, $cpzone;
2007

    
2008
	$isipv6 = is_ipaddrv6($cliip);
2009
	$interfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
2010
	foreach ($interfaces as $cpif) {
2011
		if ($isipv6) {
2012
			$ip = get_interface_ipv6($cpif);
2013
			$sn = get_interface_subnetv6($cpif);
2014
		} else {
2015
			$ip = get_interface_ip($cpif);
2016
			$sn = get_interface_subnet($cpif);
2017
		}
2018
		if (ip_in_subnet($cliip, "{$ip}/{$sn}")) {
2019
			return $ip;
2020
		}
2021
	}
2022

    
2023
	$inet = ($isipv6) ? '-inet6' : '-inet';
2024
	$iface = exec_command("/sbin/route -n get {$inet} {$cliip} | /usr/bin/awk '/interface/ { print \$2; };'");
2025
	$iface = trim($iface, "\n");
2026
	if (!empty($iface)) {
2027
		$ip = ($isipv6) ? find_interface_ipv6($iface) : find_interface_ip($iface);
2028
		if (is_ipaddr($ip)) {
2029
			return $ip;
2030
		}
2031
	}
2032

    
2033
	// doesn't match up to any particular interface
2034
	// so let's set the portal IP to what PHP says
2035
	// the server IP issuing the request is.
2036
	// allows same behavior as 1.2.x where IP isn't
2037
	// in the subnet of any CP interface (static routes, etc.)
2038
	// rather than forcing to DNS hostname resolution
2039
	$ip = $_SERVER['SERVER_ADDR'];
2040
	if (is_ipaddr($ip)) {
2041
		return $ip;
2042
	}
2043

    
2044
	return false;
2045
}
2046

    
2047
function portal_hostname_from_client_ip($cliip) {
2048
	global $config, $cpzone;
2049

    
2050
	$cpcfg = $config['captiveportal'][$cpzone];
2051

    
2052
	if (isset($cpcfg['httpslogin'])) {
2053
		$listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 8001);
2054
		$ourhostname = $cpcfg['httpsname'];
2055

    
2056
		if ($listenporthttps != 443) {
2057
			$ourhostname .= ":" . $listenporthttps;
2058
		}
2059
	} else {
2060
		$listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : ($cpcfg['zoneid'] + 8000);
2061
		$ifip = portal_ip_from_client_ip($cliip);
2062
		if (!$ifip) {
2063
			$ourhostname = "{$config['system']['hostname']}.{$config['system']['domain']}";
2064
		} else {
2065
			$ourhostname = (is_ipaddrv6($ifip)) ? "[{$ifip}]" : "{$ifip}";
2066
		}
2067

    
2068
		if ($listenporthttp != 80) {
2069
			$ourhostname .= ":" . $listenporthttp;
2070
		}
2071
	}
2072

    
2073
	return $ourhostname;
2074
}
2075

    
2076
/* functions move from index.php */
2077

    
2078
function portal_reply_page($redirurl, $type = null, $message = null, $clientmac = null, $clientip = null, $username = null, $password = null) {
2079
	global $g, $config, $cpzone;
2080

    
2081
	/* Get captive portal layout */
2082
	if ($type == "redir") {
2083
		header("Location: {$redirurl}");
2084
		return;
2085
	} else if ($type == "login") {
2086
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
2087
	} else {
2088
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
2089
	}
2090

    
2091
	$cpcfg = $config['captiveportal'][$cpzone];
2092

    
2093
	/* substitute the PORTAL_REDIRURL variable */
2094
	if ($cpcfg['preauthurl']) {
2095
		$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
2096
		$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
2097
	}
2098

    
2099
	/* substitute other variables */
2100
	$ourhostname = portal_hostname_from_client_ip($clientip);
2101
	$protocol = (isset($cpcfg['httpslogin'])) ? 'https://' : 'http://';
2102
	$htmltext = str_replace("\$PORTAL_ACTION\$", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
2103
	$htmltext = str_replace("#PORTAL_ACTION#", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
2104

    
2105
	$htmltext = str_replace("\$PORTAL_ZONE\$", htmlspecialchars($cpzone), $htmltext);
2106
	$htmltext = str_replace("\$PORTAL_REDIRURL\$", htmlspecialchars($redirurl), $htmltext);
2107
	$htmltext = str_replace("\$PORTAL_MESSAGE\$", htmlspecialchars($message), $htmltext);
2108
	$htmltext = str_replace("\$CLIENT_MAC\$", htmlspecialchars($clientmac), $htmltext);
2109
	$htmltext = str_replace("\$CLIENT_IP\$", htmlspecialchars($clientip), $htmltext);
2110

    
2111
	// Special handling case for captive portal master page so that it can be ran
2112
	// through the PHP interpreter using the include method above.  We convert the
2113
	// $VARIABLE$ case to #VARIABLE# in /etc/inc/captiveportal.inc before writing out.
2114
	$htmltext = str_replace("#PORTAL_ZONE#", htmlspecialchars($cpzone), $htmltext);
2115
	$htmltext = str_replace("#PORTAL_REDIRURL#", htmlspecialchars($redirurl), $htmltext);
2116
	$htmltext = str_replace("#PORTAL_MESSAGE#", htmlspecialchars($message), $htmltext);
2117
	$htmltext = str_replace("#CLIENT_MAC#", htmlspecialchars($clientmac), $htmltext);
2118
	$htmltext = str_replace("#CLIENT_IP#", htmlspecialchars($clientip), $htmltext);
2119
	$htmltext = str_replace("#USERNAME#", htmlspecialchars($username), $htmltext);
2120
	$htmltext = str_replace("#PASSWORD#", htmlspecialchars($password), $htmltext);
2121

    
2122
	echo $htmltext;
2123
}
2124

    
2125
function portal_mac_radius($clientmac, $clientip) {
2126
	global $config, $cpzone;
2127

    
2128
	$radmac_secret = $config['captiveportal'][$cpzone]['radmac_secret'];
2129

    
2130
	/* authentication against the radius server */
2131
	$username = mac_format($clientmac);
2132
	$auth_list = radius($username, $radmac_secret, $clientip, $clientmac, "MACHINE LOGIN");
2133
	if ($auth_list['auth_val'] == 2) {
2134
		return TRUE;
2135
	}
2136

    
2137
	if (!empty($auth_list['url_redirection'])) {
2138
		portal_reply_page($auth_list['url_redirection'], "redir");
2139
	}
2140

    
2141
	return FALSE;
2142
}
2143

    
2144
function captiveportal_reapply_attributes($cpentry, $attributes) {
2145
	global $config, $cpzone, $g;
2146

    
2147
	if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2148
		$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2149
		$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2150
	} else {
2151
		$dwfaultbw_up = $dwfaultbw_down = 0;
2152
	}
2153
	/* pipe throughputs must always be an integer, enforce that restriction again here. */
2154
	$bw_up = round(!empty($attributes['bw_up']) ? intval($attributes['bw_up'])/1000 : $dwfaultbw_up, 0);
2155
	$bw_down = round(!empty($attributes['bw_down']) ? intval($attributes['bw_down'])/1000 : $dwfaultbw_down, 0);
2156
	$bw_up_pipeno = $cpentry[1];
2157
	$bw_down_pipeno = $cpentry[1]+1;
2158

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

    
2163
	unset($bw_up_pipeno, $bw_down_pipeno, $bw_up, $bw_down);
2164
}
2165

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

    
2169
	// Ensure we create an array if we are missing attributes
2170
	if (!is_array($attributes)) {
2171
		$attributes = array();
2172
	}
2173

    
2174
	unset($sessionid);
2175

    
2176
	/* Do not allow concurrent login execution. */
2177
	$cpdblck = lock("captiveportaldb{$cpzone}", LOCK_EX);
2178

    
2179
	if ($attributes['voucher']) {
2180
		$remaining_time = $attributes['session_timeout'];
2181
	// Set RADIUS-Attribute to Voucher to prevent ReAuth-Reqeuest for Vouchers Bug: #2155
2182
		$radiusctx="voucher";
2183
	}
2184

    
2185
	$writecfg = false;
2186
	/* Find an existing session */
2187
	if ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) &&
2188
	    $passthrumac &&
2189
	    isset($config['captiveportal'][$cpzone]['passthrumacadd'])) {
2190
		$mac = captiveportal_passthrumac_findbyname($username);
2191
		if (!empty($mac) && $_POST['replacemacpassthru']) {
2192
			foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $idx => $macent) {
2193
				if ($macent['mac'] != $mac['mac']) {
2194
					continue;
2195
				}
2196

    
2197
				$macrules = "";
2198
				$pipeno = captiveportal_get_dn_passthru_ruleno($mac['mac']);
2199
				if ($pipeno) {
2200
					captiveportal_free_dn_ruleno($pipeno);
2201
					$macrules .= "table {$cpzone}_pipe_mac delete any,{$mac['mac']}\n";
2202
					$macrules .= "table {$cpzone}_pipe_mac delete {$mac['mac']},any\n";
2203
					$macrules .= "pipe delete {$pipeno}\n";
2204
					++$pipeno;
2205
					$macrules .= "pipe delete {$pipeno}\n";
2206
				}
2207
				unset($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
2208
				$mac['action'] = 'pass';
2209
				$mac['mac'] = $clientmac;
2210
				$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2211
				$macrules .= captiveportal_passthrumac_configure_entry($mac);
2212
				file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2213
				mwexec("/sbin/ipfw -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2214
				$writecfg = true;
2215
				$sessionid = true;
2216
				break;
2217
			}
2218
		} elseif (!empty($mac)) {
2219
			portal_reply_page($redirurl, "error", "Username: {$username} is already authenticated using another MAC address.",
2220
				$clientmac, $clientip, $username, $password);
2221
			unlock($cpdblck);
2222
			return;
2223
		}
2224
	}
2225

    
2226
	/* read in client database */
2227
	$query = "WHERE ip = '{$clientip}'";
2228
	$tmpusername = SQLite3::escapeString(strtolower($username));
2229
	if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
2230
		$query .= " OR (username != 'unauthenticated' AND lower(username) = '{$tmpusername}')";
2231
	}
2232
	$cpdb = captiveportal_read_db($query);
2233

    
2234
	/* Snapshot the timestamp */
2235
	$allow_time = time();
2236
	$radiusservers = captiveportal_get_radius_servers();
2237
	$unsetindexes = array();
2238
	if (is_null($radiusctx)) {
2239
		$radiusctx = 'first';
2240
	}
2241

    
2242
	foreach ($cpdb as $cpentry) {
2243
		if (empty($cpentry[11])) {
2244
			$cpentry[11] = 'first';
2245
		}
2246
		/* on the same ip */
2247
		if ($cpentry[2] == $clientip) {
2248
			if (isset($config['captiveportal'][$cpzone]['nomacfilter']) || $cpentry[3] == $clientmac) {
2249
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING OLD SESSION");
2250
			} else {
2251
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING IP {$cpentry[2]} WITH DIFFERENT MAC ADDRESS {$cpentry[3]}");
2252
			}
2253
			$sessionid = $cpentry[5];
2254
			break;
2255
		} elseif (($attributes['voucher']) && ($username != 'unauthenticated') && ($cpentry[4] == $username)) {
2256
			// user logged in with an active voucher. Check for how long and calculate
2257
			// how much time we can give him (voucher credit - used time)
2258
			$remaining_time = $cpentry[0] + $cpentry[7] - $allow_time;
2259
			if ($remaining_time < 0) { // just in case.
2260
				$remaining_time = 0;
2261
			}
2262

    
2263
			/* This user was already logged in so we disconnect the old one */
2264
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2265
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2266
			$unsetindexes[] = $cpentry[5];
2267
			break;
2268
		} elseif ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && ($username != 'unauthenticated')) {
2269
			/* on the same username */
2270
			if (strcasecmp($cpentry[4], $username) == 0) {
2271
				/* This user was already logged in so we disconnect the old one */
2272
				captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2273
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2274
				$unsetindexes[] = $cpentry[5];
2275
				break;
2276
			}
2277
		}
2278
	}
2279
	unset($cpdb);
2280

    
2281
	if (!empty($unsetindexes)) {
2282
		captiveportal_remove_entries($unsetindexes);
2283
	}
2284

    
2285
	if ($attributes['voucher'] && $remaining_time <= 0) {
2286
		return 0;       // voucher already used and no time left
2287
	}
2288

    
2289
	if (!isset($sessionid)) {
2290
		/* generate unique session ID */
2291
		$tod = gettimeofday();
2292
		$sessionid = substr(md5(mt_rand() . $tod['sec'] . $tod['usec'] . $clientip . $clientmac), 0, 16);
2293

    
2294
		if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2295
			$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2296
			$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2297
		} else {
2298
			$dwfaultbw_up = $dwfaultbw_down = 0;
2299
		}
2300
		/* pipe throughputs must always be an integer, enforce that restriction again here. */
2301
		$bw_up = round(!empty($attributes['bw_up']) ? intval($attributes['bw_up'])/1000 : $dwfaultbw_up, 0);
2302
		$bw_down = round(!empty($attributes['bw_down']) ? intval($attributes['bw_down'])/1000 : $dwfaultbw_down, 0);
2303

    
2304
		if ($passthrumac) {
2305

    
2306
			$mac = array();
2307
			$mac['action'] = 'pass';
2308
			$mac['mac'] = $clientmac;
2309
			$mac['ip'] = $clientip; /* Used only for logging */
2310
			if (isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
2311
				$mac['username'] = $username;
2312
				if ($attributes['voucher']) {
2313
					$mac['logintype'] = "voucher";
2314
				}
2315
			}
2316
			if ($username == "unauthenticated") {
2317
				$mac['descr'] = "Auto-added";
2318
			} else {
2319
				$mac['descr'] = "Auto-added for user {$username}";
2320
			}
2321
			if (!empty($bw_up)) {
2322
				$mac['bw_up'] = $bw_up;
2323
			}
2324
			if (!empty($bw_down)) {
2325
				$mac['bw_down'] = $bw_down;
2326
			}
2327
			if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2328
				$config['captiveportal'][$cpzone]['passthrumac'] = array();
2329
			}
2330
			//check for mac duplicates before adding it to config.
2331
			$mac_duplicate = false;
2332
			foreach($config['captiveportal'][$cpzone]['passthrumac'] as $mac_check){
2333
				if($mac_check['mac'] == $mac['mac']){
2334
					$mac_duplicate = true;
2335
				}
2336
			}
2337
			if(!$mac_duplicate){
2338
				$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2339
			}
2340
			unlock($cpdblck);
2341
			$macrules = captiveportal_passthrumac_configure_entry($mac);
2342
			file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2343
			mwexec("/sbin/ipfw -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2344
			$writecfg = true;
2345
		} else {
2346
			/* See if a pipeno is passed, if not start sessions because this means there isn't one atm */
2347
			if (is_null($pipeno)) {
2348
				$pipeno = captiveportal_get_next_dn_ruleno();
2349
			}
2350

    
2351
			/* if the pool is empty, return appropriate message and exit */
2352
			if (is_null($pipeno)) {
2353
				portal_reply_page($redirurl, "error", "System reached maximum login capacity");
2354
				log_error("Zone: {$cpzone} - WARNING!  Captive portal has reached maximum login capacity");
2355
				unlock($cpdblck);
2356
				return;
2357
			}
2358

    
2359
			$bw_up_pipeno = $pipeno;
2360
			$bw_down_pipeno = $pipeno + 1;
2361
			//$bw_up /= 1000; // Scale to Kbit/s
2362
			$_gb = @pfSense_ipfw_pipe("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2363
			$_gb = @pfSense_ipfw_pipe("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2364

    
2365
			$rule_entry = "{$clientip}/" . (is_ipaddrv6($clientip) ? "128" : "32");
2366
			if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) {
2367
				$rule_entry .= ",{$clientmac}";
2368
			}
2369
			$_gb = @pfSense_ipfw_table("{$cpzone}_auth_up", IP_FW_TABLE_XADD, "{$rule_entry}", $bw_up_pipeno);
2370
			$_gb = @pfSense_ipfw_table("{$cpzone}_auth_down", IP_FW_TABLE_XADD, "{$rule_entry}", $bw_down_pipeno);
2371

    
2372
			if ($attributes['voucher']) {
2373
				$attributes['session_timeout'] = $remaining_time;
2374
			}
2375

    
2376
			/* handle empty attributes */
2377
			$session_timeout = (!empty($attributes['session_timeout'])) ? $attributes['session_timeout'] : 'NULL';
2378
			$idle_timeout = (!empty($attributes['idle_timeout'])) ? $attributes['idle_timeout'] : 'NULL';
2379
			$session_terminate_time = (!empty($attributes['session_terminate_time'])) ? $attributes['session_terminate_time'] : 'NULL';
2380
			$interim_interval = (!empty($attributes['interim_interval'])) ? $attributes['interim_interval'] : 'NULL';
2381

    
2382
			/* escape username */
2383
			$safe_username = SQLite3::escapeString($username);
2384

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

    
2391
			/* store information to database */
2392
			captiveportal_write_db($insertquery);
2393
			unlock($cpdblck);
2394
			unset($insertquery, $bpassword);
2395

    
2396
			if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers[$radiusctx])) {
2397
				$acct_val = RADIUS_ACCOUNTING_START($pipeno, $username, $sessionid, $radiusservers[$radiusctx], $clientip, $clientmac);
2398
				if ($acct_val == 1) {
2399
					captiveportal_logportalauth($username, $clientmac, $clientip, $type, "RADIUS ACCOUNTING FAILED");
2400
				}
2401
			}
2402
		}
2403
	} else {
2404
		/* NOTE: #3062-11 If the pipeno has been allocated free it to not DoS the CP and maintain proper operation as in radius() case */
2405
		if (!is_null($pipeno)) {
2406
			captiveportal_free_dn_ruleno($pipeno);
2407
		}
2408

    
2409
		unlock($cpdblck);
2410
	}
2411

    
2412
	if ($writecfg == true) {
2413
		write_config(gettext("Captive Portal allowed users configuration changed"));
2414
	}
2415

    
2416
	/* redirect user to desired destination */
2417
	if (!empty($attributes['url_redirection'])) {
2418
		$my_redirurl = $attributes['url_redirection'];
2419
	} else if (!empty($redirurl)) {
2420
		$my_redirurl = $redirurl;
2421
	} else if (!empty($config['captiveportal'][$cpzone]['redirurl'])) {
2422
		$my_redirurl = $config['captiveportal'][$cpzone]['redirurl'];
2423
	}
2424

    
2425
	if (isset($config['captiveportal'][$cpzone]['logoutwin_enable']) && !$passthrumac) {
2426
		$ourhostname = portal_hostname_from_client_ip($clientip);
2427
		$protocol = (isset($config['captiveportal'][$cpzone]['httpslogin'])) ? 'https://' : 'http://';
2428
		$logouturl = "{$protocol}{$ourhostname}/";
2429

    
2430
		if (isset($attributes['reply_message'])) {
2431
			$message = $attributes['reply_message'];
2432
		} else {
2433
			$message = 0;
2434
		}
2435

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

    
2438
	} else {
2439
		portal_reply_page($my_redirurl, "redir", "Just redirect the user.");
2440
	}
2441

    
2442
	return $sessionid;
2443
}
2444

    
2445

    
2446
/*
2447
 * Used for when pass-through credits are enabled.
2448
 * Returns true when there was at least one free login to deduct for the MAC.
2449
 * Expired entries are removed as they are seen.
2450
 * Active entries are updated according to the configuration.
2451
 */
2452
function portal_consume_passthrough_credit($clientmac) {
2453
	global $config, $cpzone;
2454

    
2455
	if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count'])) {
2456
		$freeloginscount = $config['captiveportal'][$cpzone]['freelogins_count'];
2457
	} else {
2458
		return false;
2459
	}
2460

    
2461
	if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout'])) {
2462
		$resettimeout = $config['captiveportal'][$cpzone]['freelogins_resettimeout'];
2463
	} else {
2464
		return false;
2465
	}
2466

    
2467
	if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac) {
2468
		return false;
2469
	}
2470

    
2471
	$updatetimeouts = isset($config['captiveportal'][$cpzone]['freelogins_updatetimeouts']);
2472

    
2473
	/*
2474
	 * Read database of used MACs.  Lines are a comma-separated list
2475
	 * of the time, MAC, then the count of pass-through credits remaining.
2476
	 */
2477
	$usedmacs = captiveportal_read_usedmacs_db();
2478

    
2479
	$currenttime = time();
2480
	$found = false;
2481
	foreach ($usedmacs as $key => $usedmac) {
2482
		$usedmac = explode(",", $usedmac);
2483

    
2484
		if ($usedmac[1] == $clientmac) {
2485
			if ($usedmac[0] + ($resettimeout * 3600) > $currenttime) {
2486
				if ($usedmac[2] < 1) {
2487
					if ($updatetimeouts) {
2488
						$usedmac[0] = $currenttime;
2489
						unset($usedmacs[$key]);
2490
						$usedmacs[] = implode(",", $usedmac);
2491
						captiveportal_write_usedmacs_db($usedmacs);
2492
					}
2493

    
2494
					return false;
2495
				} else {
2496
					$usedmac[2] -= 1;
2497
					$usedmacs[$key] = implode(",", $usedmac);
2498
				}
2499

    
2500
				$found = true;
2501
			} else {
2502
				unset($usedmacs[$key]);
2503
			}
2504

    
2505
			break;
2506
		} else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime) {
2507
			unset($usedmacs[$key]);
2508
		}
2509
	}
2510

    
2511
	if (!$found) {
2512
		$usedmac = array($currenttime, $clientmac, $freeloginscount - 1);
2513
		$usedmacs[] = implode(",", $usedmac);
2514
	}
2515

    
2516
	captiveportal_write_usedmacs_db($usedmacs);
2517
	return true;
2518
}
2519

    
2520
function captiveportal_read_usedmacs_db() {
2521
	global $g, $cpzone;
2522

    
2523
	$cpumaclck = lock("captiveusedmacs{$cpzone}");
2524
	if (file_exists("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db")) {
2525
		$usedmacs = file("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2526
		if (!$usedmacs) {
2527
			$usedmacs = array();
2528
		}
2529
	} else {
2530
		$usedmacs = array();
2531
	}
2532

    
2533
	unlock($cpumaclck);
2534
	return $usedmacs;
2535
}
2536

    
2537
function captiveportal_write_usedmacs_db($usedmacs) {
2538
	global $g, $cpzone;
2539

    
2540
	$cpumaclck = lock("captiveusedmacs{$cpzone}", LOCK_EX);
2541
	@file_put_contents("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", implode("\n", $usedmacs));
2542
	unlock($cpumaclck);
2543
}
2544

    
2545
function captiveportal_blocked_mac($mac) {
2546
	global $config, $g, $cpzone;
2547

    
2548
	if (empty($mac) || !is_macaddr($mac)) {
2549
		return false;
2550
	}
2551

    
2552
	if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2553
		return false;
2554
	}
2555

    
2556
	foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) {
2557
		if (($passthrumac['action'] == 'block') &&
2558
		    ($passthrumac['mac'] == strtolower($mac))) {
2559
			return true;
2560
		}
2561
	}
2562

    
2563
	return false;
2564

    
2565
}
2566

    
2567
function captiveportal_send_server_accounting($off = false) {
2568
	global $cpzone, $config;
2569

    
2570
	if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
2571
		return;
2572
	}
2573
	if ($off) {
2574
		$racct = new Auth_RADIUS_Acct_Off;
2575
	} else {
2576
		$racct = new Auth_RADIUS_Acct_On;
2577
	}
2578
	$radiusservers = captiveportal_get_radius_servers();
2579
	if (empty($radiusservers)) {
2580
		return;
2581
	}
2582
	foreach ($radiusservers['first'] as $radsrv) {
2583
		// Add a new server to our instance
2584
		$racct->addServer($radsrv['ipaddr'], $radsrv['acctport'], $radsrv['key']);
2585
	}
2586
	if (PEAR::isError($racct->start())) {
2587
		$retvalue['acct_val'] = 1;
2588
		$retvalue['error'] = $racct->getMessage();
2589

    
2590
		// If we encounter an error immediately stop this function and go back
2591
		$racct->close();
2592
		return $retvalue;
2593
	}
2594
	// Send request
2595
	$result = $racct->send();
2596
	// Evaluation of the response
2597
	// 5 -> Accounting-Response
2598
	// See RFC2866 for this.
2599
	if (PEAR::isError($result)) {
2600
		$retvalue['acct_val'] = 1;
2601
		$retvalue['error'] = $result->getMessage();
2602
	} else if ($result === true) {
2603
		$retvalue['acct_val'] = 5 ;
2604
	} else {
2605
		$retvalue['acct_val'] = 1 ;
2606
	}
2607

    
2608
	$racct->close();
2609
	return $retvalue;
2610
}
2611

    
2612
function captiveportal_isip_logged($clientip) {
2613
	global $g, $cpzone;
2614

    
2615
	/* read in client database */
2616
	$query = "WHERE ip = '{$clientip}'";
2617
	$cpdb = captiveportal_read_db($query);
2618
	foreach ($cpdb as $cpentry) {
2619
		return $cpentry;
2620
	}
2621
}
2622
?>
(5-5/55)