Project

General

Profile

Download (81.3 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 in");
634
	$cprules .= captiveportal_create_ipfw_rule("add", $rulenum,
635
	    "pipe tablearg ip from any to table({$cpzone}_auth_down) 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
	file_put_contents("/tmp/debug_antes", $cprules);
667
	$cprules .= captiveportal_passthrumac_configure(true);
668
	$cprules .= "\n";
669

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

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

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

    
683
	captiveportal_filterdns_configure();
684

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

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

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

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

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

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

    
712
	$tables = captiveportal_get_ipfw_table_names();
713

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

    
719
	if (empty($delrules)) {
720
		return;
721
	}
722

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

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

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

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

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

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

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

    
761
	$radiussrvs = captiveportal_get_radius_servers();
762

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

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

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

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

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

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

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

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

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

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

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

    
923
	captiveportal_prune_old_automac();
924

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

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

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

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

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

    
999
	$stop_time = (empty($stop_time)) ? time() : $stop_time;
1000

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

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

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

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

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

    
1053
}
1054

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

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

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

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

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

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

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

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

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

    
1097
	captiveportal_radius_stop_all($term_cause, $logoutReason);
1098

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

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

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

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

    
1117
	$cpdb = captiveportal_read_db();
1118

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

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

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

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

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

    
1166
		$pipeno = captiveportal_get_next_dn_ruleno();
1167

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

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

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

    
1186
	return $rules;
1187
}
1188

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

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

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

    
1204
	return $rules;
1205
}
1206

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

    
1210
	$rules = "";
1211

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

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

    
1243
	return $rules;
1244
}
1245

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

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

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

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

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

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

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

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

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

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

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

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

    
1342
	return $rules;
1343
}
1344

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

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

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

    
1368
	return $rules;
1369
}
1370

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

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

    
1381
	return $rules;
1382
}
1383

    
1384
/* get last activity timestamp given client IP address */
1385
function captiveportal_get_last_activity($ip, $mac = NULL, $table = 1) {
1386
	global $cpzoneid;
1387

    
1388
	/* XXX Fix */
1389
	return 0;
1390
	$ipfwoutput = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, $table, $ip, $mac);
1391
	/* Reading only from one of the tables is enough of approximation. */
1392
	if (is_array($ipfwoutput)) {
1393
		/* Workaround for #46652 */
1394
		if ($ipfwoutput['packets'] > 0) {
1395
			return $ipfwoutput['timestamp'];
1396
		} else {
1397
			return 0;
1398
		}
1399
	}
1400

    
1401
	return 0;
1402
}
1403

    
1404
function captiveportal_init_radius_servers() {
1405
	global $config, $g, $cpzone;
1406

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

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

    
1441
		$radiuskey = $config['captiveportal'][$cpzone]['radiuskey'];
1442
		$radiuskey2 = $config['captiveportal'][$cpzone]['radiuskey2'];
1443
		$radiuskey3 = $config['captiveportal'][$cpzone]['radiuskey3'];
1444
		$radiuskey4 = $config['captiveportal'][$cpzone]['radiuskey4'];
1445

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

    
1466
		fclose($fd);
1467
		unlock($cprdsrvlck);
1468
	}
1469
}
1470

    
1471
/* read RADIUS servers into array */
1472
function captiveportal_get_radius_servers() {
1473
	global $g, $cpzone;
1474

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

    
1504
	unlock($cprdsrvlck);
1505
	return false;
1506
}
1507

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

    
1521
/* log simple messages to syslog */
1522
function captiveportal_syslog($message) {
1523
	global $cpzone;
1524

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

    
1533
function radius($username, $password, $clientip, $clientmac, $type, $radiusctx = null) {
1534
	global $g, $config, $cpzoneid;
1535

    
1536
	$pipeno = captiveportal_get_next_dn_ruleno();
1537

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

    
1546
	$radiusservers = captiveportal_get_radius_servers();
1547

    
1548
	if (is_null($radiusctx)) {
1549
		$radiusctx = 'first';
1550
	}
1551

    
1552
	$auth_list = RADIUS_AUTHENTICATION($username,
1553
		$password,
1554
		$radiusservers[$radiusctx],
1555
		$clientip,
1556
		$clientmac,
1557
		$pipeno);
1558

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

    
1572
	return $auth_list;
1573
}
1574

    
1575
function captiveportal_opendb() {
1576
	global $g, $config, $cpzone, $cpzoneid;
1577

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

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

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

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

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

    
1646
	return $DB;
1647
}
1648

    
1649
/* Get all tables for specific cpzone */
1650
function captiveportal_get_ipfw_table_names() {
1651
	global $cpzone;
1652

    
1653
	$result = array();
1654
	$tables = pfSense_ipfw_tables_list();
1655

    
1656
	if (!is_array($tables)) {
1657
		return $result;
1658
	}
1659

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

    
1666
		$result[] = $table['name'];
1667
	}
1668

    
1669
	return $result;
1670
}
1671

    
1672
/* read captive portal DB into array */
1673
function captiveportal_read_db($query = "") {
1674
	$cpdb = array();
1675

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

    
1687
	return $cpdb;
1688
}
1689

    
1690
function captiveportal_remove_entries($remove) {
1691

    
1692
	if (!is_array($remove) || empty($remove)) {
1693
		return;
1694
	}
1695

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

    
1707
/* write captive portal DB */
1708
function captiveportal_write_db($queries) {
1709
	global $g;
1710

    
1711
	if (is_array($queries)) {
1712
		$query = implode(";", $queries);
1713
	} else {
1714
		$query = $queries;
1715
	}
1716

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

    
1733
function captiveportal_write_elements() {
1734
	global $g, $config, $cpzone;
1735

    
1736
	$cpcfg = $config['captiveportal'][$cpzone];
1737

    
1738
	if (!is_dir($g['captiveportal_element_path'])) {
1739
		@mkdir($g['captiveportal_element_path']);
1740
	}
1741

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

    
1758
	return 0;
1759
}
1760

    
1761
function captiveportal_free_dnrules($rulenos_start = 2000, $rulenos_range_max = 64500) {
1762
	global $cpzone;
1763

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

    
1784
function captiveportal_get_next_dn_ruleno($rulenos_start = 2000, $rulenos_range_max = 64500) {
1785
	global $config, $g, $cpzone;
1786

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

    
1814
	return $ruleno;
1815
}
1816

    
1817
function captiveportal_free_dn_ruleno($ruleno) {
1818
	global $config, $g;
1819

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

    
1832
function captiveportal_get_dn_passthru_ruleno($value) {
1833
	global $config, $g, $cpzone, $cpzoneid;
1834

    
1835
	$cpcfg = $config['captiveportal'][$cpzone];
1836
	if (!isset($cpcfg['enable'])) {
1837
		return NULL;
1838
	}
1839

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

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

    
1860
	return $ruleno;
1861
}
1862

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

    
1874
function getVolume($ip, $mac = NULL) {
1875
	global $config, $cpzone, $cpzoneid;
1876

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

    
1882
	/* XXX Fix */
1883
	return $volume;
1884
	$ipfw = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, 1, $ip, $mac);
1885
	if (is_array($ipfw)) {
1886
		if ($reverse) {
1887
			$volume['output_pkts'] = $ipfw['packets'];
1888
			$volume['output_bytes'] = $ipfw['bytes'];
1889
		}
1890
		else {
1891
			$volume['input_pkts'] = $ipfw['packets'];
1892
			$volume['input_bytes'] = $ipfw['bytes'];
1893
		}
1894
	}
1895

    
1896
	$ipfw = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, 2, $ip, $mac);
1897
	if (is_array($ipfw)) {
1898
		if ($reverse) {
1899
			$volume['input_pkts'] = $ipfw['packets'];
1900
			$volume['input_bytes'] = $ipfw['bytes'];
1901
		}
1902
		else {
1903
			$volume['output_pkts'] = $ipfw['packets'];
1904
			$volume['output_bytes'] = $ipfw['bytes'];
1905
		}
1906
	}
1907

    
1908
	return $volume;
1909
}
1910

    
1911
/**
1912
 * Get the NAS-IP-Address based on the current wan address
1913
 *
1914
 * Use functions in interfaces.inc to find this out
1915
 *
1916
 */
1917

    
1918
function getNasIP() {
1919
	global $config, $cpzone;
1920

    
1921
	if (empty($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1922
			$nasIp = get_interface_ip();
1923
	} else {
1924
		if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1925
			$nasIp = $config['captiveportal'][$cpzone]['radiussrcip_attribute'];
1926
		} else {
1927
			$nasIp = get_interface_ip($config['captiveportal'][$cpzone]['radiussrcip_attribute']);
1928
		}
1929
	}
1930

    
1931
	if (!is_ipaddr($nasIp)) {
1932
		$nasIp = "0.0.0.0";
1933
	}
1934

    
1935
	return $nasIp;
1936
}
1937

    
1938
function portal_ip_from_client_ip($cliip) {
1939
	global $config, $cpzone;
1940

    
1941
	$isipv6 = is_ipaddrv6($cliip);
1942
	$interfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
1943
	foreach ($interfaces as $cpif) {
1944
		if ($isipv6) {
1945
			$ip = get_interface_ipv6($cpif);
1946
			$sn = get_interface_subnetv6($cpif);
1947
		} else {
1948
			$ip = get_interface_ip($cpif);
1949
			$sn = get_interface_subnet($cpif);
1950
		}
1951
		if (ip_in_subnet($cliip, "{$ip}/{$sn}")) {
1952
			return $ip;
1953
		}
1954
	}
1955

    
1956
	$inet = ($isipv6) ? '-inet6' : '-inet';
1957
	$iface = exec_command("/sbin/route -n get {$inet} {$cliip} | /usr/bin/awk '/interface/ { print \$2; };'");
1958
	$iface = trim($iface, "\n");
1959
	if (!empty($iface)) {
1960
		$ip = ($isipv6) ? find_interface_ipv6($iface) : find_interface_ip($iface);
1961
		if (is_ipaddr($ip)) {
1962
			return $ip;
1963
		}
1964
	}
1965

    
1966
	// doesn't match up to any particular interface
1967
	// so let's set the portal IP to what PHP says
1968
	// the server IP issuing the request is.
1969
	// allows same behavior as 1.2.x where IP isn't
1970
	// in the subnet of any CP interface (static routes, etc.)
1971
	// rather than forcing to DNS hostname resolution
1972
	$ip = $_SERVER['SERVER_ADDR'];
1973
	if (is_ipaddr($ip)) {
1974
		return $ip;
1975
	}
1976

    
1977
	return false;
1978
}
1979

    
1980
function portal_hostname_from_client_ip($cliip) {
1981
	global $config, $cpzone;
1982

    
1983
	$cpcfg = $config['captiveportal'][$cpzone];
1984

    
1985
	if (isset($cpcfg['httpslogin'])) {
1986
		$listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 8001);
1987
		$ourhostname = $cpcfg['httpsname'];
1988

    
1989
		if ($listenporthttps != 443) {
1990
			$ourhostname .= ":" . $listenporthttps;
1991
		}
1992
	} else {
1993
		$listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : ($cpcfg['zoneid'] + 8000);
1994
		$ifip = portal_ip_from_client_ip($cliip);
1995
		if (!$ifip) {
1996
			$ourhostname = "{$config['system']['hostname']}.{$config['system']['domain']}";
1997
		} else {
1998
			$ourhostname = (is_ipaddrv6($ifip)) ? "[{$ifip}]" : "{$ifip}";
1999
		}
2000

    
2001
		if ($listenporthttp != 80) {
2002
			$ourhostname .= ":" . $listenporthttp;
2003
		}
2004
	}
2005

    
2006
	return $ourhostname;
2007
}
2008

    
2009
/* functions move from index.php */
2010

    
2011
function portal_reply_page($redirurl, $type = null, $message = null, $clientmac = null, $clientip = null, $username = null, $password = null) {
2012
	global $g, $config, $cpzone;
2013

    
2014
	/* Get captive portal layout */
2015
	if ($type == "redir") {
2016
		header("Location: {$redirurl}");
2017
		return;
2018
	} else if ($type == "login") {
2019
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
2020
	} else {
2021
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
2022
	}
2023

    
2024
	$cpcfg = $config['captiveportal'][$cpzone];
2025

    
2026
	/* substitute the PORTAL_REDIRURL variable */
2027
	if ($cpcfg['preauthurl']) {
2028
		$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
2029
		$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
2030
	}
2031

    
2032
	/* substitute other variables */
2033
	$ourhostname = portal_hostname_from_client_ip($clientip);
2034
	$protocol = (isset($cpcfg['httpslogin'])) ? 'https://' : 'http://';
2035
	$htmltext = str_replace("\$PORTAL_ACTION\$", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
2036
	$htmltext = str_replace("#PORTAL_ACTION#", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
2037

    
2038
	$htmltext = str_replace("\$PORTAL_ZONE\$", htmlspecialchars($cpzone), $htmltext);
2039
	$htmltext = str_replace("\$PORTAL_REDIRURL\$", htmlspecialchars($redirurl), $htmltext);
2040
	$htmltext = str_replace("\$PORTAL_MESSAGE\$", htmlspecialchars($message), $htmltext);
2041
	$htmltext = str_replace("\$CLIENT_MAC\$", htmlspecialchars($clientmac), $htmltext);
2042
	$htmltext = str_replace("\$CLIENT_IP\$", htmlspecialchars($clientip), $htmltext);
2043

    
2044
	// Special handling case for captive portal master page so that it can be ran
2045
	// through the PHP interpreter using the include method above.  We convert the
2046
	// $VARIABLE$ case to #VARIABLE# in /etc/inc/captiveportal.inc before writing out.
2047
	$htmltext = str_replace("#PORTAL_ZONE#", htmlspecialchars($cpzone), $htmltext);
2048
	$htmltext = str_replace("#PORTAL_REDIRURL#", htmlspecialchars($redirurl), $htmltext);
2049
	$htmltext = str_replace("#PORTAL_MESSAGE#", htmlspecialchars($message), $htmltext);
2050
	$htmltext = str_replace("#CLIENT_MAC#", htmlspecialchars($clientmac), $htmltext);
2051
	$htmltext = str_replace("#CLIENT_IP#", htmlspecialchars($clientip), $htmltext);
2052
	$htmltext = str_replace("#USERNAME#", htmlspecialchars($username), $htmltext);
2053
	$htmltext = str_replace("#PASSWORD#", htmlspecialchars($password), $htmltext);
2054

    
2055
	echo $htmltext;
2056
}
2057

    
2058
function portal_mac_radius($clientmac, $clientip) {
2059
	global $config, $cpzone;
2060

    
2061
	$radmac_secret = $config['captiveportal'][$cpzone]['radmac_secret'];
2062

    
2063
	/* authentication against the radius server */
2064
	$username = mac_format($clientmac);
2065
	$auth_list = radius($username, $radmac_secret, $clientip, $clientmac, "MACHINE LOGIN");
2066
	if ($auth_list['auth_val'] == 2) {
2067
		return TRUE;
2068
	}
2069

    
2070
	if (!empty($auth_list['url_redirection'])) {
2071
		portal_reply_page($auth_list['url_redirection'], "redir");
2072
	}
2073

    
2074
	return FALSE;
2075
}
2076

    
2077
function captiveportal_reapply_attributes($cpentry, $attributes) {
2078
	global $config, $cpzone, $g;
2079

    
2080
	if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2081
		$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2082
		$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2083
	} else {
2084
		$dwfaultbw_up = $dwfaultbw_down = 0;
2085
	}
2086
	$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2087
	$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2088
	$bw_up_pipeno = $cpentry[1];
2089
	$bw_down_pipeno = $cpentry[1]+1;
2090

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

    
2095
	unset($bw_up_pipeno, $bw_down_pipeno, $bw_up, $bw_down);
2096
}
2097

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

    
2101
	// Ensure we create an array if we are missing attributes
2102
	if (!is_array($attributes)) {
2103
		$attributes = array();
2104
	}
2105

    
2106
	unset($sessionid);
2107

    
2108
	/* Do not allow concurrent login execution. */
2109
	$cpdblck = lock("captiveportaldb{$cpzone}", LOCK_EX);
2110

    
2111
	if ($attributes['voucher']) {
2112
		$remaining_time = $attributes['session_timeout'];
2113
	// Set RADIUS-Attribute to Voucher to prevent ReAuth-Reqeuest for Vouchers Bug: #2155
2114
		$radiusctx="voucher";
2115
	}
2116

    
2117
	$writecfg = false;
2118
	/* Find an existing session */
2119
	if ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) &&
2120
	    $passthrumac &&
2121
	    isset($config['captiveportal'][$cpzone]['passthrumacadd'])) {
2122
		$mac = captiveportal_passthrumac_findbyname($username);
2123
		if (!empty($mac) && $_POST['replacemacpassthru']) {
2124
			foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $idx => $macent) {
2125
				if ($macent['mac'] != $mac['mac']) {
2126
					continue;
2127
				}
2128

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

    
2158
	/* read in client database */
2159
	$query = "WHERE ip = '{$clientip}'";
2160
	$tmpusername = SQLite3::escapeString(strtolower($username));
2161
	if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
2162
		$query .= " OR (username != 'unauthenticated' AND lower(username) = '{$tmpusername}')";
2163
	}
2164
	$cpdb = captiveportal_read_db($query);
2165

    
2166
	/* Snapshot the timestamp */
2167
	$allow_time = time();
2168
	$radiusservers = captiveportal_get_radius_servers();
2169
	$unsetindexes = array();
2170
	if (is_null($radiusctx)) {
2171
		$radiusctx = 'first';
2172
	}
2173

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

    
2195
			/* This user was already logged in so we disconnect the old one */
2196
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2197
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2198
			$unsetindexes[] = $cpentry[5];
2199
			break;
2200
		} elseif ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && ($username != 'unauthenticated')) {
2201
			/* on the same username */
2202
			if (strcasecmp($cpentry[4], $username) == 0) {
2203
				/* This user was already logged in so we disconnect the old one */
2204
				captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2205
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2206
				$unsetindexes[] = $cpentry[5];
2207
				break;
2208
			}
2209
		}
2210
	}
2211
	unset($cpdb);
2212

    
2213
	if (!empty($unsetindexes)) {
2214
		captiveportal_remove_entries($unsetindexes);
2215
	}
2216

    
2217
	if ($attributes['voucher'] && $remaining_time <= 0) {
2218
		return 0;       // voucher already used and no time left
2219
	}
2220

    
2221
	if (!isset($sessionid)) {
2222
		/* generate unique session ID */
2223
		$tod = gettimeofday();
2224
		$sessionid = substr(md5(mt_rand() . $tod['sec'] . $tod['usec'] . $clientip . $clientmac), 0, 16);
2225

    
2226
		if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2227
			$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2228
			$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2229
		} else {
2230
			$dwfaultbw_up = $dwfaultbw_down = 0;
2231
		}
2232
		$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2233
		$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2234

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

    
2272
			/* if the pool is empty, return appropriate message and exit */
2273
			if (is_null($pipeno)) {
2274
				portal_reply_page($redirurl, "error", "System reached maximum login capacity");
2275
				log_error("Zone: {$cpzone} - WARNING!  Captive portal has reached maximum login capacity");
2276
				unlock($cpdblck);
2277
				return;
2278
			}
2279

    
2280
			$bw_up_pipeno = $pipeno;
2281
			$bw_down_pipeno = $pipeno + 1;
2282
			//$bw_up /= 1000; // Scale to Kbit/s
2283
			$_gb = @pfSense_ipfw_pipe("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2284
			$_gb = @pfSense_ipfw_pipe("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2285

    
2286
			$clientsn = (is_ipaddrv6($clientip)) ? 128 : 32;
2287
			$_gb = @pfSense_ipfw_table("{$cpzone}_auth_up", IP_FW_TABLE_XADD, "{$clientip}/{$clientsn}", $bw_up_pipeno);
2288
			$_gb = @pfSense_ipfw_table("{$cpzone}_auth_down", IP_FW_TABLE_XADD, "{$clientip}/{$clientsn}", $bw_down_pipeno);
2289

    
2290
			if ($attributes['voucher']) {
2291
				$attributes['session_timeout'] = $remaining_time;
2292
			}
2293

    
2294
			/* handle empty attributes */
2295
			$session_timeout = (!empty($attributes['session_timeout'])) ? $attributes['session_timeout'] : 'NULL';
2296
			$idle_timeout = (!empty($attributes['idle_timeout'])) ? $attributes['idle_timeout'] : 'NULL';
2297
			$session_terminate_time = (!empty($attributes['session_terminate_time'])) ? $attributes['session_terminate_time'] : 'NULL';
2298
			$interim_interval = (!empty($attributes['interim_interval'])) ? $attributes['interim_interval'] : 'NULL';
2299

    
2300
			/* escape username */
2301
			$safe_username = SQLite3::escapeString($username);
2302

    
2303
			/* encode password in Base64 just in case it contains commas */
2304
			$bpassword = base64_encode($password);
2305
			$insertquery = "INSERT INTO captiveportal (allow_time, pipeno, ip, mac, username, sessionid, bpassword, session_timeout, idle_timeout, session_terminate_time, interim_interval, radiusctx) ";
2306
			$insertquery .= "VALUES ({$allow_time}, {$pipeno}, '{$clientip}', '{$clientmac}', '{$safe_username}', '{$sessionid}', '{$bpassword}', ";
2307
			$insertquery .= "{$session_timeout}, {$idle_timeout}, {$session_terminate_time}, {$interim_interval}, '{$radiusctx}')";
2308

    
2309
			/* store information to database */
2310
			captiveportal_write_db($insertquery);
2311
			unlock($cpdblck);
2312
			unset($insertquery, $bpassword);
2313

    
2314
			if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers[$radiusctx])) {
2315
				$acct_val = RADIUS_ACCOUNTING_START($pipeno, $username, $sessionid, $radiusservers[$radiusctx], $clientip, $clientmac);
2316
				if ($acct_val == 1) {
2317
					captiveportal_logportalauth($username, $clientmac, $clientip, $type, "RADIUS ACCOUNTING FAILED");
2318
				}
2319
			}
2320
		}
2321
	} else {
2322
		/* NOTE: #3062-11 If the pipeno has been allocated free it to not DoS the CP and maintain proper operation as in radius() case */
2323
		if (!is_null($pipeno)) {
2324
			captiveportal_free_dn_ruleno($pipeno);
2325
		}
2326

    
2327
		unlock($cpdblck);
2328
	}
2329

    
2330
	if ($writecfg == true) {
2331
		write_config();
2332
	}
2333

    
2334
	/* redirect user to desired destination */
2335
	if (!empty($attributes['url_redirection'])) {
2336
		$my_redirurl = $attributes['url_redirection'];
2337
	} else if (!empty($redirurl)) {
2338
		$my_redirurl = $redirurl;
2339
	} else if (!empty($config['captiveportal'][$cpzone]['redirurl'])) {
2340
		$my_redirurl = $config['captiveportal'][$cpzone]['redirurl'];
2341
	}
2342

    
2343
	if (isset($config['captiveportal'][$cpzone]['logoutwin_enable']) && !$passthrumac) {
2344
		$ourhostname = portal_hostname_from_client_ip($clientip);
2345
		$protocol = (isset($config['captiveportal'][$cpzone]['httpslogin'])) ? 'https://' : 'http://';
2346
		$logouturl = "{$protocol}{$ourhostname}/";
2347

    
2348
		if (isset($attributes['reply_message'])) {
2349
			$message = $attributes['reply_message'];
2350
		} else {
2351
			$message = 0;
2352
		}
2353

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

    
2356
	} else {
2357
		portal_reply_page($my_redirurl, "redir", "Just redirect the user.");
2358
	}
2359

    
2360
	return $sessionid;
2361
}
2362

    
2363

    
2364
/*
2365
 * Used for when pass-through credits are enabled.
2366
 * Returns true when there was at least one free login to deduct for the MAC.
2367
 * Expired entries are removed as they are seen.
2368
 * Active entries are updated according to the configuration.
2369
 */
2370
function portal_consume_passthrough_credit($clientmac) {
2371
	global $config, $cpzone;
2372

    
2373
	if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count'])) {
2374
		$freeloginscount = $config['captiveportal'][$cpzone]['freelogins_count'];
2375
	} else {
2376
		return false;
2377
	}
2378

    
2379
	if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout'])) {
2380
		$resettimeout = $config['captiveportal'][$cpzone]['freelogins_resettimeout'];
2381
	} else {
2382
		return false;
2383
	}
2384

    
2385
	if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac) {
2386
		return false;
2387
	}
2388

    
2389
	$updatetimeouts = isset($config['captiveportal'][$cpzone]['freelogins_updatetimeouts']);
2390

    
2391
	/*
2392
	 * Read database of used MACs.  Lines are a comma-separated list
2393
	 * of the time, MAC, then the count of pass-through credits remaining.
2394
	 */
2395
	$usedmacs = captiveportal_read_usedmacs_db();
2396

    
2397
	$currenttime = time();
2398
	$found = false;
2399
	foreach ($usedmacs as $key => $usedmac) {
2400
		$usedmac = explode(",", $usedmac);
2401

    
2402
		if ($usedmac[1] == $clientmac) {
2403
			if ($usedmac[0] + ($resettimeout * 3600) > $currenttime) {
2404
				if ($usedmac[2] < 1) {
2405
					if ($updatetimeouts) {
2406
						$usedmac[0] = $currenttime;
2407
						unset($usedmacs[$key]);
2408
						$usedmacs[] = implode(",", $usedmac);
2409
						captiveportal_write_usedmacs_db($usedmacs);
2410
					}
2411

    
2412
					return false;
2413
				} else {
2414
					$usedmac[2] -= 1;
2415
					$usedmacs[$key] = implode(",", $usedmac);
2416
				}
2417

    
2418
				$found = true;
2419
			} else {
2420
				unset($usedmacs[$key]);
2421
			}
2422

    
2423
			break;
2424
		} else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime) {
2425
			unset($usedmacs[$key]);
2426
		}
2427
	}
2428

    
2429
	if (!$found) {
2430
		$usedmac = array($currenttime, $clientmac, $freeloginscount - 1);
2431
		$usedmacs[] = implode(",", $usedmac);
2432
	}
2433

    
2434
	captiveportal_write_usedmacs_db($usedmacs);
2435
	return true;
2436
}
2437

    
2438
function captiveportal_read_usedmacs_db() {
2439
	global $g, $cpzone;
2440

    
2441
	$cpumaclck = lock("captiveusedmacs{$cpzone}");
2442
	if (file_exists("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db")) {
2443
		$usedmacs = file("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2444
		if (!$usedmacs) {
2445
			$usedmacs = array();
2446
		}
2447
	} else {
2448
		$usedmacs = array();
2449
	}
2450

    
2451
	unlock($cpumaclck);
2452
	return $usedmacs;
2453
}
2454

    
2455
function captiveportal_write_usedmacs_db($usedmacs) {
2456
	global $g, $cpzone;
2457

    
2458
	$cpumaclck = lock("captiveusedmacs{$cpzone}", LOCK_EX);
2459
	@file_put_contents("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", implode("\n", $usedmacs));
2460
	unlock($cpumaclck);
2461
}
2462

    
2463
function captiveportal_blocked_mac($mac) {
2464
	global $config, $g, $cpzone;
2465

    
2466
	if (empty($mac) || !is_macaddr($mac)) {
2467
		return false;
2468
	}
2469

    
2470
	if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2471
		return false;
2472
	}
2473

    
2474
	foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) {
2475
		if (($passthrumac['action'] == 'block') &&
2476
		    ($passthrumac['mac'] == strtolower($mac))) {
2477
			return true;
2478
		}
2479
	}
2480

    
2481
	return false;
2482

    
2483
}
2484

    
2485
function captiveportal_send_server_accounting($off = false) {
2486
	global $cpzone, $config;
2487

    
2488
	if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
2489
		return;
2490
	}
2491
	if ($off) {
2492
		$racct = new Auth_RADIUS_Acct_Off;
2493
	} else {
2494
		$racct = new Auth_RADIUS_Acct_On;
2495
	}
2496
	$radiusservers = captiveportal_get_radius_servers();
2497
	if (empty($radiusservers)) {
2498
		return;
2499
	}
2500
	foreach ($radiusservers['first'] as $radsrv) {
2501
		// Add a new server to our instance
2502
		$racct->addServer($radsrv['ipaddr'], $radsrv['acctport'], $radsrv['key']);
2503
	}
2504
	if (PEAR::isError($racct->start())) {
2505
		$retvalue['acct_val'] = 1;
2506
		$retvalue['error'] = $racct->getMessage();
2507

    
2508
		// If we encounter an error immediately stop this function and go back
2509
		$racct->close();
2510
		return $retvalue;
2511
	}
2512
	// Send request
2513
	$result = $racct->send();
2514
	// Evaluation of the response
2515
	// 5 -> Accounting-Response
2516
	// See RFC2866 for this.
2517
	if (PEAR::isError($result)) {
2518
		$retvalue['acct_val'] = 1;
2519
		$retvalue['error'] = $result->getMessage();
2520
	} else if ($result === true) {
2521
		$retvalue['acct_val'] = 5 ;
2522
	} else {
2523
		$retvalue['acct_val'] = 1 ;
2524
	}
2525

    
2526
	$racct->close();
2527
	return $retvalue;
2528
}
2529

    
2530
function captiveportal_isip_logged($clientip) {
2531
	global $g, $cpzone;
2532

    
2533
	/* read in client database */
2534
	$query = "WHERE ip = '{$clientip}'";
2535
	$cpdb = captiveportal_read_db($query);
2536
	foreach ($cpdb as $cpentry) {
2537
		return $cpentry;
2538
	}
2539
}
2540
?>
(3-3/51)