Project

General

Profile

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

    
361
		captiveportal_delete_rules();
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);
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);
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() {
691
	global $g, $cpzoneid;
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
	if (empty($delrules)) {
719
		return;
720
	}
721

    
722
	file_put_contents("{$g['tmp_path']}/ipfw_{$cpzone}.deltable.rules", $delrules);
723
	mwexec("/sbin/ipfw -q {$g['tmp_path']}/ipfw_{$cpzone}.deltable.rules", true);
724
	@unlink("{$g['tmp_path']}/ipfw_{$cpzone}.del.rules");
725
}
726

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

    
736
	if (empty($cpzone)) {
737
		return;
738
	}
739

    
740
	$cpcfg = $config['captiveportal'][$cpzone];
741
	$vcpcfg = $config['voucher'][$cpzone];
742

    
743
	/* check for expired entries */
744
	$idletimeout = 0;
745
	$timeout = 0;
746
	if (!empty($cpcfg['timeout']) && is_numeric($cpcfg['timeout'])) {
747
		$timeout = $cpcfg['timeout'] * 60;
748
	}
749

    
750
	if (!empty($cpcfg['idletimeout']) && is_numeric($cpcfg['idletimeout'])) {
751
		$idletimeout = $cpcfg['idletimeout'] * 60;
752
	}
753

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

    
760
	$radiussrvs = captiveportal_get_radius_servers();
761

    
762
	/* Read database */
763
	/* NOTE: while this can be simplified in non radius case keep as is for now */
764
	$cpdb = captiveportal_read_db();
765

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

    
776
		$timedout = false;
777
		$term_cause = 1;
778
		if (empty($cpentry[11])) {
779
			$cpentry[11] = 'first';
780
		}
781
		$radiusservers = $radiussrvs[$cpentry[11]];
782

    
783
		/* hard timeout? */
784
		if ($timeout) {
785
			if (($pruning_time - $cpentry[0]) >= $timeout) {
786
				$timedout = true;
787
				$term_cause = 5; // Session-Timeout
788
			}
789
		}
790

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

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

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

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

    
834
		if ($timedout) {
835
			captiveportal_disconnect($cpentry, $radiusservers, $term_cause, $stop_time);
836
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "TIMEOUT");
837
			$unsetindexes[] = $cpentry[5];
838
		}
839

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

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

    
920
	captiveportal_prune_old_automac();
921

    
922
	if ($voucher_needs_sync == true) {
923
		/* Trigger a sync of the vouchers on config */
924
		send_event("service sync vouchers");
925
	}
926

    
927
	/* write database */
928
	if (!empty($unsetindexes)) {
929
		captiveportal_remove_entries($unsetindexes);
930
	}
931
}
932

    
933
function captiveportal_prune_old_automac() {
934
	global $g, $config, $cpzone, $cpzoneid;
935

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

    
992
/* remove a single client according to the DB entry */
993
function captiveportal_disconnect($dbent, $radiusservers, $term_cause = 1, $stop_time = null) {
994
	global $g, $config, $cpzone, $cpzoneid;
995

    
996
	$stop_time = (empty($stop_time)) ? time() : $stop_time;
997

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

    
1019
	if (is_ipaddr($dbent[2])) {
1020
		/*
1021
		 * Delete client's ip entry from tables auth_up and auth_down.
1022
		 *
1023
		 * It's not necessary to explicit specify mac address here
1024
		 */
1025
		$clientsn = (is_ipaddrv6($dbent[2])) ? 128 : 32;
1026
		pfSense_ipfw_table("{$cpzone}_auth_up", IP_FW_TABLE_XDEL, "{$dbent[2]}/{$clientsn}");
1027
		pfSense_ipfw_table("{$cpzone}_auth_down", IP_FW_TABLE_XDEL, "{$dbent[2]}/{$clientsn}");
1028
		/* XXX: Redundant?! Ensure all pf(4) states are killed. */
1029
		$_gb = @pfSense_kill_states($dbent[2]);
1030
		$_gb = @pfSense_kill_srcstates($dbent[2]);
1031
	}
1032

    
1033
	/*
1034
	* These are the pipe numbers we use to control traffic shaping for each logged in user via captive portal
1035
	* We could get an error if the pipe doesn't exist but everything should still be fine
1036
	*/
1037
	if (!empty($dbent[1])) {
1038
		$_gb = @pfSense_ipfw_pipe("pipe delete {$dbent[1]}");
1039
		$_gb = @pfSense_ipfw_pipe("pipe delete " . ($dbent[1]+1));
1040

    
1041
		/* Release the ruleno so it can be reallocated to new clients. */
1042
		captiveportal_free_dn_ruleno($dbent[1]);
1043
	}
1044

    
1045
	// XMLRPC Call over to the master Voucher node
1046
	if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) {
1047
		$syncip   = $config['voucher'][$cpzone]['vouchersyncdbip'];
1048
		$syncport = $config['voucher'][$cpzone]['vouchersyncport'];
1049
		$syncpass = $config['voucher'][$cpzone]['vouchersyncpass'];
1050
		$vouchersyncusername = $config['voucher'][$cpzone]['vouchersyncusername'];
1051
		$remote_status = xmlrpc_sync_voucher_disconnect($dbent, $syncip, $syncport, $syncpass, $vouchersyncusername, $term_cause, $stop_time);
1052
	}
1053

    
1054
}
1055

    
1056
/* remove a single client by sessionid */
1057
function captiveportal_disconnect_client($sessionid, $term_cause = 1, $logoutReason = "LOGOUT") {
1058
	global $g, $config;
1059

    
1060
	$sessionid = SQLite3::escapeString($sessionid);
1061
	$radiusservers = captiveportal_get_radius_servers();
1062

    
1063
	/* read database */
1064
	$result = captiveportal_read_db("WHERE sessionid = '{$sessionid}'");
1065

    
1066
	/* find entry */
1067
	if (!empty($result)) {
1068
		captiveportal_write_db("DELETE FROM captiveportal WHERE sessionid = '{$sessionid}'");
1069

    
1070
		foreach ($result as $cpentry) {
1071
			if (empty($cpentry[11])) {
1072
				$cpentry[11] = 'first';
1073
			}
1074
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], $term_cause);
1075
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "DISCONNECT");
1076
		}
1077
		unset($result);
1078
	}
1079
}
1080

    
1081
/* remove all clients */
1082
function captiveportal_disconnect_all($term_cause = 6, $logoutReason = "DISCONNECT") {
1083
	global $g, $config, $cpzone, $cpzoneid;
1084

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

    
1088
	/* if we still don't have the lock, unlock forcefully and take it */
1089
	if (!$rcprunelock) {
1090
		log_error("CP zone ${cpzone}: could not obtain the lock for more than 15 seconds, lock taken forcefully to disconnect all users");
1091
		unlock_force("rcprunecaptiveportal{$cpzone}");
1092
		$rcprunelock = lock("rcprunecaptiveportal{$cpzone}", LOCK_EX);
1093
	}
1094

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

    
1098
	captiveportal_radius_stop_all($term_cause, $logoutReason);
1099

    
1100
	/* remove users from the database */
1101
	$cpdb = captiveportal_read_db();
1102
	$unsetindexes = array_column($cpdb,5);
1103
	if (!empty($unsetindexes)) {
1104
		captiveportal_remove_entries($unsetindexes);
1105
	}
1106

    
1107
	/* reinit ipfw rules */
1108
	captiveportal_init_rules(true);
1109

    
1110
	unlock($cpdblck);
1111
	unlock($rcprunelock);
1112
}
1113

    
1114
/* send RADIUS acct stop for all current clients */
1115
function captiveportal_radius_stop_all($term_cause = 6, $logoutReason = "DISCONNECT") {
1116
	global $g, $config, $cpzone, $cpzoneid;
1117

    
1118
	$cpdb = captiveportal_read_db();
1119

    
1120
	$radacct = isset($config['captiveportal'][$cpzone]['radacct_enable']) ? true : false;
1121
	if ($radacct) {
1122
		$radiusservers = captiveportal_get_radius_servers();
1123
	}
1124

    
1125
	foreach ($cpdb as $cpentry) {
1126
		if ($radacct) {
1127
			if (!empty($radiusservers)) {
1128
				if (empty($cpentry[11])) {
1129
					$cpentry[11] = 'first';
1130
				}
1131
				if (!empty($radiusservers[$cpentry[11]])) {
1132
					RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
1133
						$cpentry[4], // username
1134
						$cpentry[5], // sessionid
1135
						$cpentry[0], // start time
1136
						$radiusservers[$cpentry[11]],
1137
						$cpentry[2], // clientip
1138
						$cpentry[3], // clientmac
1139
						$term_cause);
1140
				}
1141
			}
1142
		}
1143
		captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], $logoutReason);
1144
	}
1145
	unset($cpdb);
1146
}
1147

    
1148
function captiveportal_passthrumac_configure_entry($macent, $pipeinrule = false) {
1149
	global $config, $g, $cpzone;
1150

    
1151
	$bwUp = 0;
1152
	if (!empty($macent['bw_up'])) {
1153
		$bwUp = $macent['bw_up'];
1154
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1155
		$bwUp = $config['captiveportal'][$cpzone]['bwdefaultup'];
1156
	}
1157
	$bwDown = 0;
1158
	if (!empty($macent['bw_down'])) {
1159
		$bwDown = $macent['bw_down'];
1160
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1161
		$bwDown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1162
	}
1163

    
1164
	if ($macent['action'] == 'pass') {
1165
		$rules = "";
1166

    
1167
		$pipeno = captiveportal_get_next_dn_ruleno();
1168

    
1169
		$pipeup = $pipeno;
1170
		if ($pipeinrule == true) {
1171
			$_gb = @pfSense_ipfw_pipe("pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16");
1172
		} else {
1173
			$rules .= "pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16\n";
1174
		}
1175

    
1176
		$pipedown = $pipeno + 1;
1177
		if ($pipeinrule == true) {
1178
			$_gb = @pfSense_ipfw_pipe("pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16");
1179
		} else {
1180
			$rules .= "pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16\n";
1181
		}
1182

    
1183
		$rules .= "table {$cpzone}_pipe_mac add any,{$macent['mac']} {$pipeup}\n";
1184
		$rules .= "table {$cpzone}_pipe_mac add {$macent['mac']},any {$pipedown}\n";
1185
	}
1186

    
1187
	return $rules;
1188
}
1189

    
1190
function captiveportal_passthrumac_delete_entry($macent) {
1191
	$rules = "";
1192

    
1193
	if ($macent['action'] == 'pass') {
1194
		$pipeno = captiveportal_get_dn_passthru_ruleno($macent['mac']);
1195

    
1196
		if (!empty($pipeno)) {
1197
			captiveportal_free_dn_ruleno($pipeno);
1198
			$rules .= "table {$cpzone}_pipe_mac delete any,{$macent['mac']}\n";
1199
			$rules .= "table {$cpzone}_pipe_mac delete {$macent['mac']},any\n";
1200
			$rules .= "pipe delete " . $pipeno . "\n";
1201
			$rules .= "pipe delete " . ++$pipeno . "\n";
1202
		}
1203
	}
1204

    
1205
	return $rules;
1206
}
1207

    
1208
function captiveportal_passthrumac_configure($filename = false, $startindex = 0, $stopindex = 0) {
1209
	global $config, $g, $cpzone;
1210

    
1211
	$rules = "";
1212

    
1213
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1214
		if ($stopindex > 0) {
1215
			$fd = fopen($filename, "w");
1216
			for ($idx = $startindex; $idx <= $stopindex; $idx++) {
1217
				if (isset($config['captiveportal'][$cpzone]['passthrumac'][$idx])) {
1218
					$rules = captiveportal_passthrumac_configure_entry($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
1219
					fwrite($fd, $rules);
1220
				}
1221
			}
1222
			fclose($fd);
1223

    
1224
			return;
1225
		} else {
1226
			$nentries = count($config['captiveportal'][$cpzone]['passthrumac']);
1227
			if ($nentries > 2000) {
1228
				$nloops = $nentries / 1000;
1229
				$remainder= $nentries % 1000;
1230
				for ($i = 0; $i < $nloops; $i++) {
1231
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . ((($i+1) * 1000) - 1) . "\"");
1232
				}
1233
				if ($remainder > 0) {
1234
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . (($i* 1000) + $remainder) ."\"");
1235
				}
1236
			} else {
1237
				foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1238
					$rules .= captiveportal_passthrumac_configure_entry($macent, true);
1239
				}
1240
			}
1241
		}
1242
	}
1243

    
1244
	return $rules;
1245
}
1246

    
1247
function captiveportal_passthrumac_findbyname($username) {
1248
	global $config, $cpzone;
1249

    
1250
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1251
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1252
			if ($macent['username'] == $username) {
1253
				return $macent;
1254
			}
1255
		}
1256
	}
1257
	return NULL;
1258
}
1259

    
1260
/*
1261
 * table (3=IN)/(4=OUT) hold allowed ip's without bw limits
1262
 */
1263
function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) {
1264
	global $g, $config, $cpzone;
1265

    
1266
	/*  Instead of copying this entire function for something
1267
	 *  easy such as hostname vs ip address add this check
1268
	 */
1269
	if ($ishostname === true) {
1270
		if (!platform_booting()) {
1271
			$ipaddress = gethostbyname($ipent['hostname']);
1272
			if (!is_ipaddr($ipaddress)) {
1273
				return;
1274
			}
1275
		} else {
1276
			$ipaddress = "";
1277
		}
1278
	} else {
1279
		$ipaddress = $ipent['ip'];
1280
	}
1281

    
1282
	$rules = "";
1283
	$cp_filterdns_conf = "";
1284
	$enBwup = 0;
1285
	if (!empty($ipent['bw_up'])) {
1286
		$enBwup = intval($ipent['bw_up']);
1287
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1288
		$enBwup = $config['captiveportal'][$cpzone]['bwdefaultup'];
1289
	}
1290
	$enBwdown = 0;
1291
	if (!empty($ipent['bw_down'])) {
1292
		$enBwdown = intval($ipent['bw_down']);
1293
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1294
		$enBwdown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1295
	}
1296

    
1297
	$pipeup = captiveportal_get_next_dn_ruleno();
1298
	$_gb = @pfSense_ipfw_pipe("pipe {$pipeup} config bw {$enBwup}Kbit/s queue 100 buckets 16");
1299
	$pipedown = $pipeup + 1;
1300
	$_gb = @pfSense_ipfw_pipe("pipe {$pipedown} config bw {$enBwdown}Kbit/s queue 100 buckets 16");
1301

    
1302
	if ($ishostname === true) {
1303
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} {$cpzone}_allowed_up pipe {$pipeup}\n";
1304
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} {$cpzone}_allowed_down pipe {$pipedown}\n";
1305
		if (!is_ipaddr($ipaddress)) {
1306
			return array("", $cp_filterdns_conf);
1307
		}
1308
	}
1309

    
1310
	$subnet = "";
1311
	if (!empty($ipent['sn'])) {
1312
		$subnet = "/{$ipent['sn']}";
1313
	}
1314
	$rules .= "table {$cpzone}_allowed_up add {$ipaddress}{$subnet} {$pipeup}\n";
1315
	$rules .= "table {$cpzone}_allowed_down add {$ipaddress}{$subnet} {$pipedown}\n";
1316

    
1317
	if ($ishostname === true) {
1318
		return array($rules, $cp_filterdns_conf);
1319
	} else {
1320
		return $rules;
1321
	}
1322
}
1323

    
1324
function captiveportal_allowedhostname_configure() {
1325
	global $config, $g, $cpzone, $cpzoneid;
1326

    
1327
	$rules = "";
1328
	if (!is_array($config['captiveportal'][$cpzone]['allowedhostname'])) {
1329
		return $rules;
1330
	}
1331

    
1332
	$rules = "\n# captiveportal_allowedhostname_configure()\n";
1333
	$cp_filterdns_conf = "";
1334
	foreach ($config['captiveportal'][$cpzone]['allowedhostname'] as $hostnameent) {
1335
		$tmprules = captiveportal_allowedip_configure_entry($hostnameent, true);
1336
		$rules .= $tmprules[0];
1337
		$cp_filterdns_conf .= $tmprules[1];
1338
	}
1339
	$cp_filterdns_filename = "{$g['varetc_path']}/filterdns-{$cpzone}-captiveportal.conf";
1340
	@file_put_contents($cp_filterdns_filename, $cp_filterdns_conf);
1341
	unset($cp_filterdns_conf);
1342

    
1343
	return $rules;
1344
}
1345

    
1346
function captiveportal_filterdns_configure() {
1347
	global $config, $g, $cpzone, $cpzoneid;
1348

    
1349
	$cp_filterdns_filename = $g['varetc_path'] .
1350
	    "/filterdns-{$cpzone}-captiveportal.conf";
1351

    
1352
	if (isset($config['captiveportal'][$cpzone]['enable']) &&
1353
	    is_array($config['captiveportal'][$cpzone]['allowedhostname']) &&
1354
	    file_exists($cp_filterdns_filename)) {
1355
		if (isvalidpid($g['varrun_path'] .
1356
		    "/filterdns-{$cpzone}-cpah.pid")) {
1357
			sigkillbypid($g['varrun_path'] .
1358
			    "/filterdns-{$cpzone}-cpah.pid", "HUP");
1359
		} else {
1360
			mwexec("/usr/local/sbin/filterdns -p " .
1361
			    "{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid" .
1362
			    " -i 300 -c {$cp_filterdns_filename} -d 1");
1363
		}
1364
	} else {
1365
		killbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1366
		@unlink("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1367
	}
1368

    
1369
	return $rules;
1370
}
1371

    
1372
function captiveportal_allowedip_configure() {
1373
	global $config, $g, $cpzone;
1374

    
1375
	$rules = "";
1376
	if (is_array($config['captiveportal'][$cpzone]['allowedip'])) {
1377
		foreach ($config['captiveportal'][$cpzone]['allowedip'] as $ipent) {
1378
			$rules .= captiveportal_allowedip_configure_entry($ipent);
1379
		}
1380
	}
1381

    
1382
	return $rules;
1383
}
1384

    
1385
/* get last activity timestamp given client IP address */
1386
function captiveportal_get_last_activity($ip) {
1387
	global $cpzone;
1388

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

    
1392
	foreach ($tables as $table) {
1393
		$ipfw = pfSense_ipfw_table_lookup($table, $ip);
1394
		if (is_array($ipfw)) {
1395
			/* Workaround for #46652 */
1396
			if ($ipfw['packets'] > 0) {
1397
				return $ipfw['timestamp'];
1398
			} else {
1399
				return 0;
1400
			}
1401
		}
1402
	}
1403

    
1404
	return 0;
1405
}
1406

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

    
1410
	/* generate radius server database */
1411
	if ($config['captiveportal'][$cpzone]['radiusip'] &&
1412
	    (!isset($config['captiveportal'][$cpzone]['auth_method']) || $config['captiveportal'][$cpzone]['auth_method'] == "radius")) {
1413
		$radiusip = $config['captiveportal'][$cpzone]['radiusip'];
1414
		$radiusip2 = ($config['captiveportal'][$cpzone]['radiusip2']) ? $config['captiveportal'][$cpzone]['radiusip2'] : null;
1415
		$radiusip3 = ($config['captiveportal'][$cpzone]['radiusip3']) ? $config['captiveportal'][$cpzone]['radiusip3'] : null;
1416
		$radiusip4 = ($config['captiveportal'][$cpzone]['radiusip4']) ? $config['captiveportal'][$cpzone]['radiusip4'] : null;
1417

    
1418
		if ($config['captiveportal'][$cpzone]['radiusport']) {
1419
			$radiusport = $config['captiveportal'][$cpzone]['radiusport'];
1420
		} else {
1421
			$radiusport = 1812;
1422
		}
1423
		if ($config['captiveportal'][$cpzone]['radiusacctport']) {
1424
			$radiusacctport = $config['captiveportal'][$cpzone]['radiusacctport'];
1425
		} else {
1426
			$radiusacctport = 1813;
1427
		}
1428
		if ($config['captiveportal'][$cpzone]['radiusport2']) {
1429
			$radiusport2 = $config['captiveportal'][$cpzone]['radiusport2'];
1430
		} else {
1431
			$radiusport2 = 1812;
1432
		}
1433
		if ($config['captiveportal'][$cpzone]['radiusport3']) {
1434
			$radiusport3 = $config['captiveportal'][$cpzone]['radiusport3'];
1435
		} else {
1436
			$radiusport3 = 1812;
1437
		}
1438
		if ($config['captiveportal'][$cpzone]['radiusport4']) {
1439
			$radiusport4 = $config['captiveportal'][$cpzone]['radiusport4'];
1440
		} else {
1441
			$radiusport4 = 1812;
1442
		}
1443

    
1444
		$radiuskey = $config['captiveportal'][$cpzone]['radiuskey'];
1445
		$radiuskey2 = $config['captiveportal'][$cpzone]['radiuskey2'];
1446
		$radiuskey3 = $config['captiveportal'][$cpzone]['radiuskey3'];
1447
		$radiuskey4 = $config['captiveportal'][$cpzone]['radiuskey4'];
1448

    
1449
		$cprdsrvlck = lock("captiveportalradius{$cpzone}", LOCK_EX);
1450
		$fd = @fopen("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db", "w");
1451
		if (!$fd) {
1452
			captiveportal_syslog("Error: cannot open RADIUS DB file in captiveportal_configure().\n");
1453
			unlock($cprdsrvlck);
1454
			return 1;
1455
		}
1456
		if (isset($radiusip)) {
1457
			fwrite($fd, $radiusip . "," . $radiusport . "," . $radiusacctport . "," . $radiuskey . ",first");
1458
		}
1459
		if (isset($radiusip2)) {
1460
			fwrite($fd, "\n" . $radiusip2 . "," . $radiusport2 . "," . $radiusacctport . "," . $radiuskey2 . ",first");
1461
		}
1462
		if (isset($radiusip3)) {
1463
			fwrite($fd, "\n" . $radiusip3 . "," . $radiusport3 . "," . $radiusacctport . "," . $radiuskey3 . ",second");
1464
		}
1465
		if (isset($radiusip4)) {
1466
			fwrite($fd, "\n" . $radiusip4 . "," . $radiusport4 . "," . $radiusacctport . "," . $radiuskey4 . ",second");
1467
		}
1468

    
1469
		fclose($fd);
1470
		unlock($cprdsrvlck);
1471
	}
1472
}
1473

    
1474
/* read RADIUS servers into array */
1475
function captiveportal_get_radius_servers() {
1476
	global $g, $cpzone;
1477

    
1478
	$cprdsrvlck = lock("captiveportalradius{$cpzone}");
1479
	if (file_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db")) {
1480
		$radiusservers = array();
1481
		$cpradiusdb = file("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db",
1482
		FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1483
		if ($cpradiusdb) {
1484
			foreach ($cpradiusdb as $cpradiusentry) {
1485
				$line = trim($cpradiusentry);
1486
				if ($line) {
1487
					$radsrv = array();
1488
					list($radsrv['ipaddr'], $radsrv['port'], $radsrv['acctport'], $radsrv['key'], $context) = explode(",", $line);
1489
				}
1490
				if (empty($context)) {
1491
					if (!is_array($radiusservers['first'])) {
1492
						$radiusservers['first'] = array();
1493
					}
1494
					$radiusservers['first'] = $radsrv;
1495
				} else {
1496
					if (!is_array($radiusservers[$context])) {
1497
						$radiusservers[$context] = array();
1498
					}
1499
					$radiusservers[$context][] = $radsrv;
1500
				}
1501
			}
1502
		}
1503
		unlock($cprdsrvlck);
1504
		return $radiusservers;
1505
	}
1506

    
1507
	unlock($cprdsrvlck);
1508
	return false;
1509
}
1510

    
1511
/* log successful captive portal authentication to syslog */
1512
/* part of this code from php.net */
1513
function captiveportal_logportalauth($user, $mac, $ip, $status, $message = null) {
1514
	// Log it
1515
	if (!$message) {
1516
		$message = "{$status}: {$user}, {$mac}, {$ip}";
1517
	} else {
1518
		$message = trim($message);
1519
		$message = "{$status}: {$user}, {$mac}, {$ip}, {$message}";
1520
	}
1521
	captiveportal_syslog($message);
1522
}
1523

    
1524
/* log simple messages to syslog */
1525
function captiveportal_syslog($message) {
1526
	global $cpzone;
1527

    
1528
	$message = trim($message);
1529
	$message = "Zone: {$cpzone} - {$message}";
1530
	openlog("logportalauth", LOG_PID, LOG_LOCAL4);
1531
	// Log it
1532
	syslog(LOG_INFO, $message);
1533
	closelog();
1534
}
1535

    
1536
function radius($username, $password, $clientip, $clientmac, $type, $radiusctx = null) {
1537
	global $g, $config, $cpzoneid;
1538

    
1539
	$pipeno = captiveportal_get_next_dn_ruleno();
1540

    
1541
	/* If the pool is empty, return appropriate message and fail authentication */
1542
	if (empty($pipeno)) {
1543
		$auth_list = array();
1544
		$auth_list['auth_val'] = 1;
1545
		$auth_list['error'] = "System reached maximum login capacity";
1546
		return $auth_list;
1547
	}
1548

    
1549
	$radiusservers = captiveportal_get_radius_servers();
1550

    
1551
	if (is_null($radiusctx)) {
1552
		$radiusctx = 'first';
1553
	}
1554

    
1555
	$auth_list = RADIUS_AUTHENTICATION($username,
1556
		$password,
1557
		$radiusservers[$radiusctx],
1558
		$clientip,
1559
		$clientmac,
1560
		$pipeno);
1561

    
1562
	if ($auth_list['auth_val'] == 2) {
1563
		captiveportal_logportalauth($username, $clientmac, $clientip, $type);
1564
		$sessionid = portal_allow($clientip,
1565
			$clientmac,
1566
			$username,
1567
			$password,
1568
			$auth_list,
1569
			$pipeno,
1570
			$radiusctx);
1571
	} else {
1572
		captiveportal_free_dn_ruleno($pipeno);
1573
	}
1574

    
1575
	return $auth_list;
1576
}
1577

    
1578
function captiveportal_opendb() {
1579
	global $g, $config, $cpzone, $cpzoneid;
1580

    
1581
	$db_path = "{$g['vardb_path']}/captiveportal{$cpzone}.db";
1582
	$createquery = "CREATE TABLE IF NOT EXISTS captiveportal (" .
1583
				"allow_time INTEGER, pipeno INTEGER, ip TEXT, mac TEXT, username TEXT, " .
1584
				"sessionid TEXT, bpassword TEXT, session_timeout INTEGER, idle_timeout INTEGER, " .
1585
				"session_terminate_time INTEGER, interim_interval INTEGER, radiusctx TEXT); " .
1586
			"CREATE UNIQUE INDEX IF NOT EXISTS idx_active ON captiveportal (sessionid, username); " .
1587
			"CREATE INDEX IF NOT EXISTS user ON captiveportal (username); " .
1588
			"CREATE INDEX IF NOT EXISTS ip ON captiveportal (ip); " .
1589
			"CREATE INDEX IF NOT EXISTS starttime ON captiveportal (allow_time)";
1590

    
1591
	try {
1592
		$DB = new SQLite3($db_path);
1593
		$DB->busyTimeout(60000);
1594
	} catch (Exception $e) {
1595
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: " . $e->getMessage() . " -- Trying again.");
1596
		unlink_if_exists($db_path);
1597
		try {
1598
			$DB = new SQLite3($db_path);
1599
			$DB->busyTimeout(60000);
1600
		} catch (Exception $e) {
1601
			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.");
1602
			return;
1603
		}
1604
	}
1605

    
1606
	if (!$DB) {
1607
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Trying again.");
1608
		unlink_if_exists($db_path);
1609
		$DB = new SQLite3($db_path);
1610
		$DB->busyTimeout(60000);
1611
		if (!$DB) {
1612
			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.");
1613
			return;
1614
		}
1615
	}
1616

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

    
1620
		/* If unable to initialize the database, reset and try again. */
1621
		$DB->close();
1622
		unset($DB);
1623
		unlink_if_exists($db_path);
1624
		$DB = new SQLite3($db_path);
1625
		$DB->busyTimeout(60000);
1626
		if ($DB->exec($createquery)) {
1627
			captiveportal_syslog("Successfully reinitialized tables for {$cpzone} -- database has been reset.");
1628
			if (!is_numericint($cpzoneid)) {
1629
				if (is_array($config['captiveportal'])) {
1630
					foreach ($config['captiveportal'] as $cpkey => $cp) {
1631
						if ($cpzone == $cpkey) {
1632
							$cpzoneid = $cp['zoneid'];
1633
						}
1634
					}
1635
				}
1636
			}
1637
			if (is_numericint($cpzoneid)) {
1638
				$table_names = captiveportal_get_ipfw_table_names();
1639
				foreach ($table_names as $table_name) {
1640
					mwexec("/sbin/ipfw table {$table_name} flush");
1641
				}
1642
				captiveportal_syslog("Flushed tables for {$cpzone} after database reset.");
1643
			}
1644
		} else {
1645
			captiveportal_syslog("Still unable to create tables for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Remove the database file manually and try again.");
1646
		}
1647
	}
1648

    
1649
	return $DB;
1650
}
1651

    
1652
/* Get all tables for specific cpzone */
1653
function captiveportal_get_ipfw_table_names() {
1654
	global $cpzone;
1655

    
1656
	$result = array();
1657
	$tables = pfSense_ipfw_tables_list();
1658

    
1659
	if (!is_array($tables)) {
1660
		return $result;
1661
	}
1662

    
1663
	$len = strlen($cpzone) + 1;
1664
	foreach ($tables as $table) {
1665
		if (substr($table['name'], 0, $len) != $cpzone . '_') {
1666
			continue;
1667
		}
1668

    
1669
		$result[] = $table['name'];
1670
	}
1671

    
1672
	return $result;
1673
}
1674

    
1675
/* read captive portal DB into array */
1676
function captiveportal_read_db($query = "") {
1677
	$cpdb = array();
1678

    
1679
	$DB = captiveportal_opendb();
1680
	if ($DB) {
1681
		$response = $DB->query("SELECT * FROM captiveportal {$query}");
1682
		if ($response != FALSE) {
1683
			while ($row = $response->fetchArray()) {
1684
				$cpdb[] = $row;
1685
			}
1686
		}
1687
		$DB->close();
1688
	}
1689

    
1690
	return $cpdb;
1691
}
1692

    
1693
function captiveportal_remove_entries($remove) {
1694

    
1695
	if (!is_array($remove) || empty($remove)) {
1696
		return;
1697
	}
1698

    
1699
	$query = "DELETE FROM captiveportal WHERE sessionid in (";
1700
	foreach ($remove as $idx => $unindex) {
1701
		$query .= "'{$unindex}'";
1702
		if ($idx < (count($remove) - 1)) {
1703
			$query .= ",";
1704
		}
1705
	}
1706
	$query .= ")";
1707
	captiveportal_write_db($query);
1708
}
1709

    
1710
/* write captive portal DB */
1711
function captiveportal_write_db($queries) {
1712
	global $g;
1713

    
1714
	if (is_array($queries)) {
1715
		$query = implode(";", $queries);
1716
	} else {
1717
		$query = $queries;
1718
	}
1719

    
1720
	$DB = captiveportal_opendb();
1721
	if ($DB) {
1722
		$DB->exec("BEGIN TRANSACTION");
1723
		$result = $DB->exec($query);
1724
		if (!$result) {
1725
			captiveportal_syslog("Trying to modify DB returned error: {$DB->lastErrorMsg()}");
1726
		} else {
1727
			$DB->exec("END TRANSACTION");
1728
		}
1729
		$DB->close();
1730
		return $result;
1731
	} else {
1732
		return true;
1733
	}
1734
}
1735

    
1736
function captiveportal_write_elements() {
1737
	global $g, $config, $cpzone;
1738

    
1739
	$cpcfg = $config['captiveportal'][$cpzone];
1740

    
1741
	if (!is_dir($g['captiveportal_element_path'])) {
1742
		@mkdir($g['captiveportal_element_path']);
1743
	}
1744

    
1745
	if (is_array($cpcfg['element'])) {
1746
		foreach ($cpcfg['element'] as $data) {
1747
			/* Do not attempt to decode or write out empty files. */
1748
			if (empty($data['content']) || empty(base64_decode($data['content']))) {
1749
				unlink_if_exists("{$g['captiveportal_element_path']}/{$data['name']}");
1750
				touch("{$g['captiveportal_element_path']}/{$data['name']}");
1751
			} elseif (!@file_put_contents("{$g['captiveportal_element_path']}/{$data['name']}", base64_decode($data['content']))) {
1752
				printf(gettext('Error: cannot open \'%1$s\' in captiveportal_write_elements()%2$s'), $data['name'], "\n");
1753
				return 1;
1754
			}
1755
			if (!file_exists("{$g['captiveportal_path']}/{$data['name']}")) {
1756
				@symlink("{$g['captiveportal_element_path']}/{$data['name']}", "{$g['captiveportal_path']}/{$data['name']}");
1757
			}
1758
		}
1759
	}
1760

    
1761
	return 0;
1762
}
1763

    
1764
function captiveportal_free_dnrules($rulenos_start = 2000, $rulenos_range_max = 64500) {
1765
	global $cpzone;
1766

    
1767
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1768
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1769
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1770
		$ridx = $rulenos_start;
1771
		while ($ridx < $rulenos_range_max) {
1772
			if ($rules[$ridx] == $cpzone) {
1773
				$rules[$ridx] = false;
1774
				$ridx++;
1775
				$rules[$ridx] = false;
1776
				$ridx++;
1777
			} else {
1778
				$ridx += 2;
1779
			}
1780
		}
1781
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1782
		unset($rules);
1783
	}
1784
	unlock($cpruleslck);
1785
}
1786

    
1787
function captiveportal_get_next_dn_ruleno($rulenos_start = 2000, $rulenos_range_max = 64500) {
1788
	global $config, $g, $cpzone;
1789

    
1790
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1791
	$ruleno = 0;
1792
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1793
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1794
		$ridx = $rulenos_start;
1795
		while ($ridx < $rulenos_range_max) {
1796
			if (empty($rules[$ridx])) {
1797
				$ruleno = $ridx;
1798
				$rules[$ridx] = $cpzone;
1799
				$ridx++;
1800
				$rules[$ridx] = $cpzone;
1801
				break;
1802
			} else {
1803
				$ridx += 2;
1804
			}
1805
		}
1806
	} else {
1807
		$rules = array_pad(array(), $rulenos_range_max, false);
1808
		$ruleno = $rulenos_start;
1809
		$rules[$rulenos_start] = $cpzone;
1810
		$rulenos_start++;
1811
		$rules[$rulenos_start] = $cpzone;
1812
	}
1813
	file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1814
	unlock($cpruleslck);
1815
	unset($rules);
1816

    
1817
	return $ruleno;
1818
}
1819

    
1820
function captiveportal_free_dn_ruleno($ruleno) {
1821
	global $config, $g;
1822

    
1823
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1824
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1825
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1826
		$rules[$ruleno] = false;
1827
		$ruleno++;
1828
		$rules[$ruleno] = false;
1829
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1830
		unset($rules);
1831
	}
1832
	unlock($cpruleslck);
1833
}
1834

    
1835
function captiveportal_get_dn_passthru_ruleno($value) {
1836
	global $config, $g, $cpzone, $cpzoneid;
1837

    
1838
	$cpcfg = $config['captiveportal'][$cpzone];
1839
	if (!isset($cpcfg['enable'])) {
1840
		return NULL;
1841
	}
1842

    
1843
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1844
	$ruleno = NULL;
1845
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1846
		unset($output);
1847
		$item = pfSense_ipfw_table_lookup("{$cpzone}_pipe_mac",
1848
		    "any,{$value}");
1849
		if (!is_array($item) || empty($item['pipe'])) {
1850
			unlock($cpruleslck);
1851
			return NULL;
1852
		}
1853

    
1854
		$ruleno = intval($item['pipe']);
1855
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1856
		if (!$rules[$ruleno]) {
1857
			$ruleno = NULL;
1858
		}
1859
		unset($rules);
1860
	}
1861
	unlock($cpruleslck);
1862

    
1863
	return $ruleno;
1864
}
1865

    
1866
/**
1867
 * This function will calculate the traffic produced by a client
1868
 * based on its firewall rule
1869
 *
1870
 * Point of view: NAS
1871
 *
1872
 * Input means: from the client
1873
 * Output means: to the client
1874
 *
1875
 */
1876

    
1877
function getVolume($ip) {
1878
	global $config, $cpzone;
1879

    
1880
	$reverse = isset($config['captiveportal'][$cpzone]['reverseacct'])
1881
	    ? true : false;
1882
	$volume = array();
1883
	// Initialize vars properly, since we don't want NULL vars
1884
	$volume['input_pkts'] = $volume['input_bytes'] = 0;
1885
	$volume['output_pkts'] = $volume['output_bytes'] = 0;
1886

    
1887
	$tables = array("allowed", "auth");
1888

    
1889
	foreach($tables as $table) {
1890
		$ipfw = pfSense_ipfw_table_lookup("{$cpzone}_{$table}_up", $ip);
1891
		if (!is_array($ipfw)) {
1892
			continue;
1893
		}
1894
		if ($reverse) {
1895
			$volume['output_pkts'] = $ipfw['packets'];
1896
			$volume['output_bytes'] = $ipfw['bytes'];
1897
		} else {
1898
			$volume['input_pkts'] = $ipfw['packets'];
1899
			$volume['input_bytes'] = $ipfw['bytes'];
1900
		}
1901
	}
1902

    
1903
	foreach($tables as $table) {
1904
		$ipfw = pfSense_ipfw_table_lookup("{$cpzone}_{$table}_down",
1905
		    $ip);
1906
		if (!is_array($ipfw)) {
1907
			continue;
1908
		}
1909
		if ($reverse) {
1910
			$volume['input_pkts'] = $ipfw['packets'];
1911
			$volume['input_bytes'] = $ipfw['bytes'];
1912
		} else {
1913
			$volume['output_pkts'] = $ipfw['packets'];
1914
			$volume['output_bytes'] = $ipfw['bytes'];
1915
		}
1916
	}
1917

    
1918
	return $volume;
1919
}
1920

    
1921
/**
1922
 * Get the NAS-IP-Address based on the current wan address
1923
 *
1924
 * Use functions in interfaces.inc to find this out
1925
 *
1926
 */
1927

    
1928
function getNasIP() {
1929
	global $config, $cpzone;
1930

    
1931
	if (empty($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1932
			$nasIp = get_interface_ip();
1933
	} else {
1934
		if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1935
			$nasIp = $config['captiveportal'][$cpzone]['radiussrcip_attribute'];
1936
		} else {
1937
			$nasIp = get_interface_ip($config['captiveportal'][$cpzone]['radiussrcip_attribute']);
1938
		}
1939
	}
1940

    
1941
	if (!is_ipaddr($nasIp)) {
1942
		$nasIp = "0.0.0.0";
1943
	}
1944

    
1945
	return $nasIp;
1946
}
1947

    
1948
function portal_ip_from_client_ip($cliip) {
1949
	global $config, $cpzone;
1950

    
1951
	$isipv6 = is_ipaddrv6($cliip);
1952
	$interfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
1953
	foreach ($interfaces as $cpif) {
1954
		if ($isipv6) {
1955
			$ip = get_interface_ipv6($cpif);
1956
			$sn = get_interface_subnetv6($cpif);
1957
		} else {
1958
			$ip = get_interface_ip($cpif);
1959
			$sn = get_interface_subnet($cpif);
1960
		}
1961
		if (ip_in_subnet($cliip, "{$ip}/{$sn}")) {
1962
			return $ip;
1963
		}
1964
	}
1965

    
1966
	$inet = ($isipv6) ? '-inet6' : '-inet';
1967
	$iface = exec_command("/sbin/route -n get {$inet} {$cliip} | /usr/bin/awk '/interface/ { print \$2; };'");
1968
	$iface = trim($iface, "\n");
1969
	if (!empty($iface)) {
1970
		$ip = ($isipv6) ? find_interface_ipv6($iface) : find_interface_ip($iface);
1971
		if (is_ipaddr($ip)) {
1972
			return $ip;
1973
		}
1974
	}
1975

    
1976
	// doesn't match up to any particular interface
1977
	// so let's set the portal IP to what PHP says
1978
	// the server IP issuing the request is.
1979
	// allows same behavior as 1.2.x where IP isn't
1980
	// in the subnet of any CP interface (static routes, etc.)
1981
	// rather than forcing to DNS hostname resolution
1982
	$ip = $_SERVER['SERVER_ADDR'];
1983
	if (is_ipaddr($ip)) {
1984
		return $ip;
1985
	}
1986

    
1987
	return false;
1988
}
1989

    
1990
function portal_hostname_from_client_ip($cliip) {
1991
	global $config, $cpzone;
1992

    
1993
	$cpcfg = $config['captiveportal'][$cpzone];
1994

    
1995
	if (isset($cpcfg['httpslogin'])) {
1996
		$listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 8001);
1997
		$ourhostname = $cpcfg['httpsname'];
1998

    
1999
		if ($listenporthttps != 443) {
2000
			$ourhostname .= ":" . $listenporthttps;
2001
		}
2002
	} else {
2003
		$listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : ($cpcfg['zoneid'] + 8000);
2004
		$ifip = portal_ip_from_client_ip($cliip);
2005
		if (!$ifip) {
2006
			$ourhostname = "{$config['system']['hostname']}.{$config['system']['domain']}";
2007
		} else {
2008
			$ourhostname = (is_ipaddrv6($ifip)) ? "[{$ifip}]" : "{$ifip}";
2009
		}
2010

    
2011
		if ($listenporthttp != 80) {
2012
			$ourhostname .= ":" . $listenporthttp;
2013
		}
2014
	}
2015

    
2016
	return $ourhostname;
2017
}
2018

    
2019
/* functions move from index.php */
2020

    
2021
function portal_reply_page($redirurl, $type = null, $message = null, $clientmac = null, $clientip = null, $username = null, $password = null) {
2022
	global $g, $config, $cpzone;
2023

    
2024
	/* Get captive portal layout */
2025
	if ($type == "redir") {
2026
		header("Location: {$redirurl}");
2027
		return;
2028
	} else if ($type == "login") {
2029
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
2030
	} else {
2031
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
2032
	}
2033

    
2034
	$cpcfg = $config['captiveportal'][$cpzone];
2035

    
2036
	/* substitute the PORTAL_REDIRURL variable */
2037
	if ($cpcfg['preauthurl']) {
2038
		$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
2039
		$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
2040
	}
2041

    
2042
	/* substitute other variables */
2043
	$ourhostname = portal_hostname_from_client_ip($clientip);
2044
	$protocol = (isset($cpcfg['httpslogin'])) ? 'https://' : 'http://';
2045
	$htmltext = str_replace("\$PORTAL_ACTION\$", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
2046
	$htmltext = str_replace("#PORTAL_ACTION#", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
2047

    
2048
	$htmltext = str_replace("\$PORTAL_ZONE\$", htmlspecialchars($cpzone), $htmltext);
2049
	$htmltext = str_replace("\$PORTAL_REDIRURL\$", htmlspecialchars($redirurl), $htmltext);
2050
	$htmltext = str_replace("\$PORTAL_MESSAGE\$", htmlspecialchars($message), $htmltext);
2051
	$htmltext = str_replace("\$CLIENT_MAC\$", htmlspecialchars($clientmac), $htmltext);
2052
	$htmltext = str_replace("\$CLIENT_IP\$", htmlspecialchars($clientip), $htmltext);
2053

    
2054
	// Special handling case for captive portal master page so that it can be ran
2055
	// through the PHP interpreter using the include method above.  We convert the
2056
	// $VARIABLE$ case to #VARIABLE# in /etc/inc/captiveportal.inc before writing out.
2057
	$htmltext = str_replace("#PORTAL_ZONE#", htmlspecialchars($cpzone), $htmltext);
2058
	$htmltext = str_replace("#PORTAL_REDIRURL#", htmlspecialchars($redirurl), $htmltext);
2059
	$htmltext = str_replace("#PORTAL_MESSAGE#", htmlspecialchars($message), $htmltext);
2060
	$htmltext = str_replace("#CLIENT_MAC#", htmlspecialchars($clientmac), $htmltext);
2061
	$htmltext = str_replace("#CLIENT_IP#", htmlspecialchars($clientip), $htmltext);
2062
	$htmltext = str_replace("#USERNAME#", htmlspecialchars($username), $htmltext);
2063
	$htmltext = str_replace("#PASSWORD#", htmlspecialchars($password), $htmltext);
2064

    
2065
	echo $htmltext;
2066
}
2067

    
2068
function portal_mac_radius($clientmac, $clientip) {
2069
	global $config, $cpzone;
2070

    
2071
	$radmac_secret = $config['captiveportal'][$cpzone]['radmac_secret'];
2072

    
2073
	/* authentication against the radius server */
2074
	$username = mac_format($clientmac);
2075
	$auth_list = radius($username, $radmac_secret, $clientip, $clientmac, "MACHINE LOGIN");
2076
	if ($auth_list['auth_val'] == 2) {
2077
		return TRUE;
2078
	}
2079

    
2080
	if (!empty($auth_list['url_redirection'])) {
2081
		portal_reply_page($auth_list['url_redirection'], "redir");
2082
	}
2083

    
2084
	return FALSE;
2085
}
2086

    
2087
function captiveportal_reapply_attributes($cpentry, $attributes) {
2088
	global $config, $cpzone, $g;
2089

    
2090
	if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2091
		$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2092
		$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2093
	} else {
2094
		$dwfaultbw_up = $dwfaultbw_down = 0;
2095
	}
2096
	$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2097
	$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2098
	$bw_up_pipeno = $cpentry[1];
2099
	$bw_down_pipeno = $cpentry[1]+1;
2100

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

    
2105
	unset($bw_up_pipeno, $bw_down_pipeno, $bw_up, $bw_down);
2106
}
2107

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

    
2111
	// Ensure we create an array if we are missing attributes
2112
	if (!is_array($attributes)) {
2113
		$attributes = array();
2114
	}
2115

    
2116
	unset($sessionid);
2117

    
2118
	/* Do not allow concurrent login execution. */
2119
	$cpdblck = lock("captiveportaldb{$cpzone}", LOCK_EX);
2120

    
2121
	if ($attributes['voucher']) {
2122
		$remaining_time = $attributes['session_timeout'];
2123
	// Set RADIUS-Attribute to Voucher to prevent ReAuth-Reqeuest for Vouchers Bug: #2155
2124
		$radiusctx="voucher";
2125
	}
2126

    
2127
	$writecfg = false;
2128
	/* Find an existing session */
2129
	if ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) &&
2130
	    $passthrumac &&
2131
	    isset($config['captiveportal'][$cpzone]['passthrumacadd'])) {
2132
		$mac = captiveportal_passthrumac_findbyname($username);
2133
		if (!empty($mac) && $_POST['replacemacpassthru']) {
2134
			foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $idx => $macent) {
2135
				if ($macent['mac'] != $mac['mac']) {
2136
					continue;
2137
				}
2138

    
2139
				$macrules = "";
2140
				$pipeno = captiveportal_get_dn_passthru_ruleno($mac['mac']);
2141
				if ($pipeno) {
2142
					captiveportal_free_dn_ruleno($pipeno);
2143
					$macrules .= "table {$cpzone}_pipe_mac delete any,{$mac['mac']}\n";
2144
					$macrules .= "table {$cpzone}_pipe_mac delete {$mac['mac']},any\n";
2145
					$macrules .= "pipe delete {$pipeno}\n";
2146
					++$pipeno;
2147
					$macrules .= "pipe delete {$pipeno}\n";
2148
				}
2149
				unset($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
2150
				$mac['action'] = 'pass';
2151
				$mac['mac'] = $clientmac;
2152
				$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2153
				$macrules .= captiveportal_passthrumac_configure_entry($mac);
2154
				file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2155
				mwexec("/sbin/ipfw -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2156
				$writecfg = true;
2157
				$sessionid = true;
2158
				break;
2159
			}
2160
		} elseif (!empty($mac)) {
2161
			portal_reply_page($redirurl, "error", "Username: {$username} is already authenticated using another MAC address.",
2162
				$clientmac, $clientip, $username, $password);
2163
			unlock($cpdblck);
2164
			return;
2165
		}
2166
	}
2167

    
2168
	/* read in client database */
2169
	$query = "WHERE ip = '{$clientip}'";
2170
	$tmpusername = SQLite3::escapeString(strtolower($username));
2171
	if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
2172
		$query .= " OR (username != 'unauthenticated' AND lower(username) = '{$tmpusername}')";
2173
	}
2174
	$cpdb = captiveportal_read_db($query);
2175

    
2176
	/* Snapshot the timestamp */
2177
	$allow_time = time();
2178
	$radiusservers = captiveportal_get_radius_servers();
2179
	$unsetindexes = array();
2180
	if (is_null($radiusctx)) {
2181
		$radiusctx = 'first';
2182
	}
2183

    
2184
	foreach ($cpdb as $cpentry) {
2185
		if (empty($cpentry[11])) {
2186
			$cpentry[11] = 'first';
2187
		}
2188
		/* on the same ip */
2189
		if ($cpentry[2] == $clientip) {
2190
			if (isset($config['captiveportal'][$cpzone]['nomacfilter']) || $cpentry[3] == $clientmac) {
2191
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING OLD SESSION");
2192
			} else {
2193
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING IP {$cpentry[2]} WITH DIFFERENT MAC ADDRESS {$cpentry[3]}");
2194
			}
2195
			$sessionid = $cpentry[5];
2196
			break;
2197
		} elseif (($attributes['voucher']) && ($username != 'unauthenticated') && ($cpentry[4] == $username)) {
2198
			// user logged in with an active voucher. Check for how long and calculate
2199
			// how much time we can give him (voucher credit - used time)
2200
			$remaining_time = $cpentry[0] + $cpentry[7] - $allow_time;
2201
			if ($remaining_time < 0) { // just in case.
2202
				$remaining_time = 0;
2203
			}
2204

    
2205
			/* This user was already logged in so we disconnect the old one */
2206
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2207
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2208
			$unsetindexes[] = $cpentry[5];
2209
			break;
2210
		} elseif ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && ($username != 'unauthenticated')) {
2211
			/* on the same username */
2212
			if (strcasecmp($cpentry[4], $username) == 0) {
2213
				/* This user was already logged in so we disconnect the old one */
2214
				captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2215
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2216
				$unsetindexes[] = $cpentry[5];
2217
				break;
2218
			}
2219
		}
2220
	}
2221
	unset($cpdb);
2222

    
2223
	if (!empty($unsetindexes)) {
2224
		captiveportal_remove_entries($unsetindexes);
2225
	}
2226

    
2227
	if ($attributes['voucher'] && $remaining_time <= 0) {
2228
		return 0;       // voucher already used and no time left
2229
	}
2230

    
2231
	if (!isset($sessionid)) {
2232
		/* generate unique session ID */
2233
		$tod = gettimeofday();
2234
		$sessionid = substr(md5(mt_rand() . $tod['sec'] . $tod['usec'] . $clientip . $clientmac), 0, 16);
2235

    
2236
		if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2237
			$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2238
			$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2239
		} else {
2240
			$dwfaultbw_up = $dwfaultbw_down = 0;
2241
		}
2242
		$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2243
		$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2244

    
2245
		if ($passthrumac) {
2246
			$mac = array();
2247
			$mac['action'] = 'pass';
2248
			$mac['mac'] = $clientmac;
2249
			$mac['ip'] = $clientip; /* Used only for logging */
2250
			if (isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
2251
				$mac['username'] = $username;
2252
				if ($attributes['voucher']) {
2253
					$mac['logintype'] = "voucher";
2254
				}
2255
			}
2256
			if ($username == "unauthenticated") {
2257
				$mac['descr'] = "Auto-added";
2258
			} else {
2259
				$mac['descr'] = "Auto-added for user {$username}";
2260
			}
2261
			if (!empty($bw_up)) {
2262
				$mac['bw_up'] = $bw_up;
2263
			}
2264
			if (!empty($bw_down)) {
2265
				$mac['bw_down'] = $bw_down;
2266
			}
2267
			if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2268
				$config['captiveportal'][$cpzone]['passthrumac'] = array();
2269
			}
2270
			$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2271
			unlock($cpdblck);
2272
			$macrules = captiveportal_passthrumac_configure_entry($mac);
2273
			file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2274
			mwexec("/sbin/ipfw -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2275
			$writecfg = true;
2276
		} else {
2277
			/* See if a pipeno is passed, if not start sessions because this means there isn't one atm */
2278
			if (is_null($pipeno)) {
2279
				$pipeno = captiveportal_get_next_dn_ruleno();
2280
			}
2281

    
2282
			/* if the pool is empty, return appropriate message and exit */
2283
			if (is_null($pipeno)) {
2284
				portal_reply_page($redirurl, "error", "System reached maximum login capacity");
2285
				log_error("Zone: {$cpzone} - WARNING!  Captive portal has reached maximum login capacity");
2286
				unlock($cpdblck);
2287
				return;
2288
			}
2289

    
2290
			$bw_up_pipeno = $pipeno;
2291
			$bw_down_pipeno = $pipeno + 1;
2292
			//$bw_up /= 1000; // Scale to Kbit/s
2293
			$_gb = @pfSense_ipfw_pipe("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2294
			$_gb = @pfSense_ipfw_pipe("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2295

    
2296
			$rule_entry = "{$clientip}/" . (is_ipaddrv6($clientip) ? "128" : "32");
2297
			if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) {
2298
				$rule_entry .= ",{$clientmac}";
2299
			}
2300
			$_gb = @pfSense_ipfw_table("{$cpzone}_auth_up", IP_FW_TABLE_XADD, "{$rule_entry}", $bw_up_pipeno);
2301
			$_gb = @pfSense_ipfw_table("{$cpzone}_auth_down", IP_FW_TABLE_XADD, "{$rule_entry}", $bw_down_pipeno);
2302

    
2303
			if ($attributes['voucher']) {
2304
				$attributes['session_timeout'] = $remaining_time;
2305
			}
2306

    
2307
			/* handle empty attributes */
2308
			$session_timeout = (!empty($attributes['session_timeout'])) ? $attributes['session_timeout'] : 'NULL';
2309
			$idle_timeout = (!empty($attributes['idle_timeout'])) ? $attributes['idle_timeout'] : 'NULL';
2310
			$session_terminate_time = (!empty($attributes['session_terminate_time'])) ? $attributes['session_terminate_time'] : 'NULL';
2311
			$interim_interval = (!empty($attributes['interim_interval'])) ? $attributes['interim_interval'] : 'NULL';
2312

    
2313
			/* escape username */
2314
			$safe_username = SQLite3::escapeString($username);
2315

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

    
2322
			/* store information to database */
2323
			captiveportal_write_db($insertquery);
2324
			unlock($cpdblck);
2325
			unset($insertquery, $bpassword);
2326

    
2327
			if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers[$radiusctx])) {
2328
				$acct_val = RADIUS_ACCOUNTING_START($pipeno, $username, $sessionid, $radiusservers[$radiusctx], $clientip, $clientmac);
2329
				if ($acct_val == 1) {
2330
					captiveportal_logportalauth($username, $clientmac, $clientip, $type, "RADIUS ACCOUNTING FAILED");
2331
				}
2332
			}
2333
		}
2334
	} else {
2335
		/* NOTE: #3062-11 If the pipeno has been allocated free it to not DoS the CP and maintain proper operation as in radius() case */
2336
		if (!is_null($pipeno)) {
2337
			captiveportal_free_dn_ruleno($pipeno);
2338
		}
2339

    
2340
		unlock($cpdblck);
2341
	}
2342

    
2343
	if ($writecfg == true) {
2344
		write_config(gettext("Captive Portal allowed users configuration changed"));
2345
	}
2346

    
2347
	/* redirect user to desired destination */
2348
	if (!empty($attributes['url_redirection'])) {
2349
		$my_redirurl = $attributes['url_redirection'];
2350
	} else if (!empty($redirurl)) {
2351
		$my_redirurl = $redirurl;
2352
	} else if (!empty($config['captiveportal'][$cpzone]['redirurl'])) {
2353
		$my_redirurl = $config['captiveportal'][$cpzone]['redirurl'];
2354
	}
2355

    
2356
	if (isset($config['captiveportal'][$cpzone]['logoutwin_enable']) && !$passthrumac) {
2357
		$ourhostname = portal_hostname_from_client_ip($clientip);
2358
		$protocol = (isset($config['captiveportal'][$cpzone]['httpslogin'])) ? 'https://' : 'http://';
2359
		$logouturl = "{$protocol}{$ourhostname}/";
2360

    
2361
		if (isset($attributes['reply_message'])) {
2362
			$message = $attributes['reply_message'];
2363
		} else {
2364
			$message = 0;
2365
		}
2366

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

    
2369
	} else {
2370
		portal_reply_page($my_redirurl, "redir", "Just redirect the user.");
2371
	}
2372

    
2373
	return $sessionid;
2374
}
2375

    
2376

    
2377
/*
2378
 * Used for when pass-through credits are enabled.
2379
 * Returns true when there was at least one free login to deduct for the MAC.
2380
 * Expired entries are removed as they are seen.
2381
 * Active entries are updated according to the configuration.
2382
 */
2383
function portal_consume_passthrough_credit($clientmac) {
2384
	global $config, $cpzone;
2385

    
2386
	if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count'])) {
2387
		$freeloginscount = $config['captiveportal'][$cpzone]['freelogins_count'];
2388
	} else {
2389
		return false;
2390
	}
2391

    
2392
	if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout'])) {
2393
		$resettimeout = $config['captiveportal'][$cpzone]['freelogins_resettimeout'];
2394
	} else {
2395
		return false;
2396
	}
2397

    
2398
	if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac) {
2399
		return false;
2400
	}
2401

    
2402
	$updatetimeouts = isset($config['captiveportal'][$cpzone]['freelogins_updatetimeouts']);
2403

    
2404
	/*
2405
	 * Read database of used MACs.  Lines are a comma-separated list
2406
	 * of the time, MAC, then the count of pass-through credits remaining.
2407
	 */
2408
	$usedmacs = captiveportal_read_usedmacs_db();
2409

    
2410
	$currenttime = time();
2411
	$found = false;
2412
	foreach ($usedmacs as $key => $usedmac) {
2413
		$usedmac = explode(",", $usedmac);
2414

    
2415
		if ($usedmac[1] == $clientmac) {
2416
			if ($usedmac[0] + ($resettimeout * 3600) > $currenttime) {
2417
				if ($usedmac[2] < 1) {
2418
					if ($updatetimeouts) {
2419
						$usedmac[0] = $currenttime;
2420
						unset($usedmacs[$key]);
2421
						$usedmacs[] = implode(",", $usedmac);
2422
						captiveportal_write_usedmacs_db($usedmacs);
2423
					}
2424

    
2425
					return false;
2426
				} else {
2427
					$usedmac[2] -= 1;
2428
					$usedmacs[$key] = implode(",", $usedmac);
2429
				}
2430

    
2431
				$found = true;
2432
			} else {
2433
				unset($usedmacs[$key]);
2434
			}
2435

    
2436
			break;
2437
		} else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime) {
2438
			unset($usedmacs[$key]);
2439
		}
2440
	}
2441

    
2442
	if (!$found) {
2443
		$usedmac = array($currenttime, $clientmac, $freeloginscount - 1);
2444
		$usedmacs[] = implode(",", $usedmac);
2445
	}
2446

    
2447
	captiveportal_write_usedmacs_db($usedmacs);
2448
	return true;
2449
}
2450

    
2451
function captiveportal_read_usedmacs_db() {
2452
	global $g, $cpzone;
2453

    
2454
	$cpumaclck = lock("captiveusedmacs{$cpzone}");
2455
	if (file_exists("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db")) {
2456
		$usedmacs = file("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2457
		if (!$usedmacs) {
2458
			$usedmacs = array();
2459
		}
2460
	} else {
2461
		$usedmacs = array();
2462
	}
2463

    
2464
	unlock($cpumaclck);
2465
	return $usedmacs;
2466
}
2467

    
2468
function captiveportal_write_usedmacs_db($usedmacs) {
2469
	global $g, $cpzone;
2470

    
2471
	$cpumaclck = lock("captiveusedmacs{$cpzone}", LOCK_EX);
2472
	@file_put_contents("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", implode("\n", $usedmacs));
2473
	unlock($cpumaclck);
2474
}
2475

    
2476
function captiveportal_blocked_mac($mac) {
2477
	global $config, $g, $cpzone;
2478

    
2479
	if (empty($mac) || !is_macaddr($mac)) {
2480
		return false;
2481
	}
2482

    
2483
	if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2484
		return false;
2485
	}
2486

    
2487
	foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) {
2488
		if (($passthrumac['action'] == 'block') &&
2489
		    ($passthrumac['mac'] == strtolower($mac))) {
2490
			return true;
2491
		}
2492
	}
2493

    
2494
	return false;
2495

    
2496
}
2497

    
2498
function captiveportal_send_server_accounting($off = false) {
2499
	global $cpzone, $config;
2500

    
2501
	if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
2502
		return;
2503
	}
2504
	if ($off) {
2505
		$racct = new Auth_RADIUS_Acct_Off;
2506
	} else {
2507
		$racct = new Auth_RADIUS_Acct_On;
2508
	}
2509
	$radiusservers = captiveportal_get_radius_servers();
2510
	if (empty($radiusservers)) {
2511
		return;
2512
	}
2513
	foreach ($radiusservers['first'] as $radsrv) {
2514
		// Add a new server to our instance
2515
		$racct->addServer($radsrv['ipaddr'], $radsrv['acctport'], $radsrv['key']);
2516
	}
2517
	if (PEAR::isError($racct->start())) {
2518
		$retvalue['acct_val'] = 1;
2519
		$retvalue['error'] = $racct->getMessage();
2520

    
2521
		// If we encounter an error immediately stop this function and go back
2522
		$racct->close();
2523
		return $retvalue;
2524
	}
2525
	// Send request
2526
	$result = $racct->send();
2527
	// Evaluation of the response
2528
	// 5 -> Accounting-Response
2529
	// See RFC2866 for this.
2530
	if (PEAR::isError($result)) {
2531
		$retvalue['acct_val'] = 1;
2532
		$retvalue['error'] = $result->getMessage();
2533
	} else if ($result === true) {
2534
		$retvalue['acct_val'] = 5 ;
2535
	} else {
2536
		$retvalue['acct_val'] = 1 ;
2537
	}
2538

    
2539
	$racct->close();
2540
	return $retvalue;
2541
}
2542

    
2543
function captiveportal_isip_logged($clientip) {
2544
	global $g, $cpzone;
2545

    
2546
	/* read in client database */
2547
	$query = "WHERE ip = '{$clientip}'";
2548
	$cpdb = captiveportal_read_db($query);
2549
	foreach ($cpdb as $cpentry) {
2550
		return $cpentry;
2551
	}
2552
}
2553
?>
(5-5/54)