Project

General

Profile

Download (81.8 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
		$pipes_to_remove = captiveportal_free_dnrules();
360

    
361
		captiveportal_delete_rules($pipes_to_remove);
362

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

    
382
	unlock($captiveportallck);
383

    
384
	return 0;
385
}
386

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
511
	return $rule;
512
}
513

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

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

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

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

    
529
	captiveportal_load_modules();
530
	captiveportal_init_general_rules();
531

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

    
536
	$skipto = captiveportal_ipfw_ruleno($cpzoneid);
537

    
538
	$cprules = '';
539

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

    
553
		$cpipm = get_interface_ip($cpifgrp);
554

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
682
	captiveportal_filterdns_configure();
683

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

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

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

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

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

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

    
711
	$tables = captiveportal_get_ipfw_table_names();
712

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

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

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

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

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

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

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

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

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

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

    
764
	$radiussrvs = captiveportal_get_radius_servers();
765

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

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

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

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

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

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

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

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

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

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

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

    
924
	captiveportal_prune_old_automac();
925

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

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

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

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

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

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

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

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

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

    
1045
		/* Release the ruleno so it can be reallocated to new clients. */
1046
		captiveportal_free_dn_ruleno($dbent[1]);
1047
	}
1048

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

    
1058
}
1059

    
1060
/* remove a single client by sessionid */
1061
function captiveportal_disconnect_client($sessionid, $term_cause = 1, $logoutReason = "LOGOUT") {
1062
	global $g, $config;
1063

    
1064
	$sessionid = SQLite3::escapeString($sessionid);
1065
	$radiusservers = captiveportal_get_radius_servers();
1066

    
1067
	/* read database */
1068
	$result = captiveportal_read_db("WHERE sessionid = '{$sessionid}'");
1069

    
1070
	/* find entry */
1071
	if (!empty($result)) {
1072
		captiveportal_write_db("DELETE FROM captiveportal WHERE sessionid = '{$sessionid}'");
1073

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

    
1085
/* remove all clients */
1086
function captiveportal_disconnect_all($term_cause = 6, $logoutReason = "DISCONNECT") {
1087
	global $g, $config, $cpzone, $cpzoneid;
1088

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

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

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

    
1102
	captiveportal_radius_stop_all($term_cause, $logoutReason);
1103

    
1104
	/* remove users from the database */
1105
	$cpdb = captiveportal_read_db();
1106
	$unsetindexes = array_column($cpdb,5);
1107
	if (!empty($unsetindexes)) {
1108
		captiveportal_remove_entries($unsetindexes);
1109
	}
1110

    
1111
	/* reinit ipfw rules */
1112
	captiveportal_init_rules(true);
1113

    
1114
	unlock($cpdblck);
1115
	unlock($rcprunelock);
1116
}
1117

    
1118
/* send RADIUS acct stop for all current clients */
1119
function captiveportal_radius_stop_all($term_cause = 6, $logoutReason = "DISCONNECT") {
1120
	global $g, $config, $cpzone, $cpzoneid;
1121

    
1122
	$cpdb = captiveportal_read_db();
1123

    
1124
	$radacct = isset($config['captiveportal'][$cpzone]['radacct_enable']) ? true : false;
1125
	if ($radacct) {
1126
		$radiusservers = captiveportal_get_radius_servers();
1127
	}
1128

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

    
1152
function captiveportal_passthrumac_configure_entry($macent, $pipeinrule = false) {
1153
	global $config, $g, $cpzone;
1154

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

    
1168
	if ($macent['action'] == 'pass') {
1169
		$rules = "";
1170

    
1171
		$pipeno = captiveportal_get_next_dn_ruleno();
1172

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

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

    
1187
		$rules .= "table {$cpzone}_pipe_mac add any,{$macent['mac']} {$pipeup}\n";
1188
		$rules .= "table {$cpzone}_pipe_mac add {$macent['mac']},any {$pipedown}\n";
1189
	}
1190

    
1191
	return $rules;
1192
}
1193

    
1194
function captiveportal_passthrumac_delete_entry($macent) {
1195
	$rules = "";
1196

    
1197
	if ($macent['action'] == 'pass') {
1198
		$pipeno = captiveportal_get_dn_passthru_ruleno($macent['mac']);
1199

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

    
1209
	return $rules;
1210
}
1211

    
1212
function captiveportal_passthrumac_configure($filename = false, $startindex = 0, $stopindex = 0) {
1213
	global $config, $g, $cpzone;
1214

    
1215
	$rules = "";
1216

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

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

    
1248
	return $rules;
1249
}
1250

    
1251
function captiveportal_passthrumac_findbyname($username) {
1252
	global $config, $cpzone;
1253

    
1254
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1255
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1256
			if ($macent['username'] == $username) {
1257
				return $macent;
1258
			}
1259
		}
1260
	}
1261
	return NULL;
1262
}
1263

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

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

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

    
1301
	$pipeup = captiveportal_get_next_dn_ruleno();
1302
	$_gb = @pfSense_ipfw_pipe("pipe {$pipeup} config bw {$enBwup}Kbit/s queue 100 buckets 16");
1303
	$pipedown = $pipeup + 1;
1304
	$_gb = @pfSense_ipfw_pipe("pipe {$pipedown} config bw {$enBwdown}Kbit/s queue 100 buckets 16");
1305

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

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

    
1321
	if ($ishostname === true) {
1322
		return array($rules, $cp_filterdns_conf);
1323
	} else {
1324
		return $rules;
1325
	}
1326
}
1327

    
1328
function captiveportal_allowedhostname_configure() {
1329
	global $config, $g, $cpzone, $cpzoneid;
1330

    
1331
	$rules = "";
1332
	if (!is_array($config['captiveportal'][$cpzone]['allowedhostname'])) {
1333
		return $rules;
1334
	}
1335

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

    
1347
	return $rules;
1348
}
1349

    
1350
function captiveportal_filterdns_configure() {
1351
	global $config, $g, $cpzone, $cpzoneid;
1352

    
1353
	$cp_filterdns_filename = $g['varetc_path'] .
1354
	    "/filterdns-{$cpzone}-captiveportal.conf";
1355

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

    
1373
	return $rules;
1374
}
1375

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

    
1379
	$rules = "";
1380
	if (is_array($config['captiveportal'][$cpzone]['allowedip'])) {
1381
		foreach ($config['captiveportal'][$cpzone]['allowedip'] as $ipent) {
1382
			$rules .= captiveportal_allowedip_configure_entry($ipent);
1383
		}
1384
	}
1385

    
1386
	return $rules;
1387
}
1388

    
1389
/* get last activity timestamp given client IP address */
1390
function captiveportal_get_last_activity($ip) {
1391
	global $cpzone;
1392

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

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

    
1408
	return 0;
1409
}
1410

    
1411
function captiveportal_init_radius_servers() {
1412
	global $config, $g, $cpzone;
1413

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

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

    
1448
		$radiuskey = $config['captiveportal'][$cpzone]['radiuskey'];
1449
		$radiuskey2 = $config['captiveportal'][$cpzone]['radiuskey2'];
1450
		$radiuskey3 = $config['captiveportal'][$cpzone]['radiuskey3'];
1451
		$radiuskey4 = $config['captiveportal'][$cpzone]['radiuskey4'];
1452

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

    
1473
		fclose($fd);
1474
		unlock($cprdsrvlck);
1475
	}
1476
}
1477

    
1478
/* read RADIUS servers into array */
1479
function captiveportal_get_radius_servers() {
1480
	global $g, $cpzone;
1481

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

    
1511
	unlock($cprdsrvlck);
1512
	return false;
1513
}
1514

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

    
1528
/* log simple messages to syslog */
1529
function captiveportal_syslog($message) {
1530
	global $cpzone;
1531

    
1532
	$message = trim($message);
1533
	$message = "Zone: {$cpzone} - {$message}";
1534
	openlog("logportalauth", LOG_PID, LOG_LOCAL4);
1535
	// Log it
1536
	syslog(LOG_INFO, $message);
1537
	closelog();
1538
}
1539

    
1540
function radius($username, $password, $clientip, $clientmac, $type, $radiusctx = null) {
1541
	global $g, $config, $cpzoneid;
1542

    
1543
	$pipeno = captiveportal_get_next_dn_ruleno();
1544

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

    
1553
	$radiusservers = captiveportal_get_radius_servers();
1554

    
1555
	if (is_null($radiusctx)) {
1556
		$radiusctx = 'first';
1557
	}
1558

    
1559
	$auth_list = RADIUS_AUTHENTICATION($username,
1560
		$password,
1561
		$radiusservers[$radiusctx],
1562
		$clientip,
1563
		$clientmac,
1564
		$pipeno);
1565

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

    
1579
	return $auth_list;
1580
}
1581

    
1582
function captiveportal_opendb() {
1583
	global $g, $config, $cpzone, $cpzoneid;
1584

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

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

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

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

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

    
1653
	return $DB;
1654
}
1655

    
1656
/* Get all tables for specific cpzone */
1657
function captiveportal_get_ipfw_table_names() {
1658
	global $cpzone;
1659

    
1660
	$result = array();
1661
	$tables = pfSense_ipfw_tables_list();
1662

    
1663
	if (!is_array($tables)) {
1664
		return $result;
1665
	}
1666

    
1667
	$len = strlen($cpzone) + 1;
1668
	foreach ($tables as $table) {
1669
		if (substr($table['name'], 0, $len) != $cpzone . '_') {
1670
			continue;
1671
		}
1672

    
1673
		$result[] = $table['name'];
1674
	}
1675

    
1676
	return $result;
1677
}
1678

    
1679
/* read captive portal DB into array */
1680
function captiveportal_read_db($query = "") {
1681
	$cpdb = array();
1682

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

    
1694
	return $cpdb;
1695
}
1696

    
1697
function captiveportal_remove_entries($remove) {
1698

    
1699
	if (!is_array($remove) || empty($remove)) {
1700
		return;
1701
	}
1702

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

    
1714
/* write captive portal DB */
1715
function captiveportal_write_db($queries) {
1716
	global $g;
1717

    
1718
	if (is_array($queries)) {
1719
		$query = implode(";", $queries);
1720
	} else {
1721
		$query = $queries;
1722
	}
1723

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

    
1740
function captiveportal_write_elements() {
1741
	global $g, $config, $cpzone;
1742

    
1743
	$cpcfg = $config['captiveportal'][$cpzone];
1744

    
1745
	if (!is_dir($g['captiveportal_element_path'])) {
1746
		@mkdir($g['captiveportal_element_path']);
1747
	}
1748

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

    
1765
	return 0;
1766
}
1767

    
1768
function captiveportal_free_dnrules($rulenos_start = 2000, $rulenos_range_max = 64500) {
1769
	global $g, $cpzone;
1770

    
1771
	$removed_pipes = array();
1772

    
1773
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1774
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1775
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1776
		$ridx = $rulenos_start;
1777
		while ($ridx < $rulenos_range_max) {
1778
			if ($rules[$ridx] == $cpzone) {
1779
				$rules[$ridx] = false;
1780
				$removed_pipes[] = $ridx;
1781
				$ridx++;
1782
				$rules[$ridx] = false;
1783
				$removed_pipes[] = $ridx;
1784
				$ridx++;
1785
			} else {
1786
				$ridx += 2;
1787
			}
1788
		}
1789
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1790
		unset($rules);
1791
	}
1792
	unlock($cpruleslck);
1793

    
1794
	return $removed_pipes;
1795
}
1796

    
1797
function captiveportal_get_next_dn_ruleno($rulenos_start = 2000, $rulenos_range_max = 64500) {
1798
	global $config, $g, $cpzone;
1799

    
1800
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1801
	$ruleno = 0;
1802
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1803
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1804
		$ridx = $rulenos_start;
1805
		while ($ridx < $rulenos_range_max) {
1806
			if (empty($rules[$ridx])) {
1807
				$ruleno = $ridx;
1808
				$rules[$ridx] = $cpzone;
1809
				$ridx++;
1810
				$rules[$ridx] = $cpzone;
1811
				break;
1812
			} else {
1813
				$ridx += 2;
1814
			}
1815
		}
1816
	} else {
1817
		$rules = array_pad(array(), $rulenos_range_max, false);
1818
		$ruleno = $rulenos_start;
1819
		$rules[$rulenos_start] = $cpzone;
1820
		$rulenos_start++;
1821
		$rules[$rulenos_start] = $cpzone;
1822
	}
1823
	file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1824
	unlock($cpruleslck);
1825
	unset($rules);
1826

    
1827
	return $ruleno;
1828
}
1829

    
1830
function captiveportal_free_dn_ruleno($ruleno) {
1831
	global $config, $g;
1832

    
1833
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1834
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1835
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1836
		$rules[$ruleno] = false;
1837
		$ruleno++;
1838
		$rules[$ruleno] = false;
1839
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1840
		unset($rules);
1841
	}
1842
	unlock($cpruleslck);
1843
}
1844

    
1845
function captiveportal_get_dn_passthru_ruleno($value) {
1846
	global $config, $g, $cpzone, $cpzoneid;
1847

    
1848
	$cpcfg = $config['captiveportal'][$cpzone];
1849
	if (!isset($cpcfg['enable'])) {
1850
		return NULL;
1851
	}
1852

    
1853
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1854
	$ruleno = NULL;
1855
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1856
		unset($output);
1857
		$item = pfSense_ipfw_table_lookup("{$cpzone}_pipe_mac",
1858
		    "any,{$value}");
1859
		if (!is_array($item) || empty($item['pipe'])) {
1860
			unlock($cpruleslck);
1861
			return NULL;
1862
		}
1863

    
1864
		$ruleno = intval($item['pipe']);
1865
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1866
		if (!$rules[$ruleno]) {
1867
			$ruleno = NULL;
1868
		}
1869
		unset($rules);
1870
	}
1871
	unlock($cpruleslck);
1872

    
1873
	return $ruleno;
1874
}
1875

    
1876
/**
1877
 * This function will calculate the traffic produced by a client
1878
 * based on its firewall rule
1879
 *
1880
 * Point of view: NAS
1881
 *
1882
 * Input means: from the client
1883
 * Output means: to the client
1884
 *
1885
 */
1886

    
1887
function getVolume($ip) {
1888
	global $config, $cpzone;
1889

    
1890
	$reverse = isset($config['captiveportal'][$cpzone]['reverseacct'])
1891
	    ? true : false;
1892
	$volume = array();
1893
	// Initialize vars properly, since we don't want NULL vars
1894
	$volume['input_pkts'] = $volume['input_bytes'] = 0;
1895
	$volume['output_pkts'] = $volume['output_bytes'] = 0;
1896

    
1897
	$tables = array("allowed", "auth");
1898

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

    
1913
	foreach($tables as $table) {
1914
		$ipfw = pfSense_ipfw_table_lookup("{$cpzone}_{$table}_down",
1915
		    $ip);
1916
		if (!is_array($ipfw)) {
1917
			continue;
1918
		}
1919
		if ($reverse) {
1920
			$volume['input_pkts'] = $ipfw['packets'];
1921
			$volume['input_bytes'] = $ipfw['bytes'];
1922
		} else {
1923
			$volume['output_pkts'] = $ipfw['packets'];
1924
			$volume['output_bytes'] = $ipfw['bytes'];
1925
		}
1926
	}
1927

    
1928
	return $volume;
1929
}
1930

    
1931
/**
1932
 * Get the NAS-IP-Address based on the current wan address
1933
 *
1934
 * Use functions in interfaces.inc to find this out
1935
 *
1936
 */
1937

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

    
1941
	if (empty($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1942
			$nasIp = get_interface_ip();
1943
	} else {
1944
		if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1945
			$nasIp = $config['captiveportal'][$cpzone]['radiussrcip_attribute'];
1946
		} else {
1947
			$nasIp = get_interface_ip($config['captiveportal'][$cpzone]['radiussrcip_attribute']);
1948
		}
1949
	}
1950

    
1951
	if (!is_ipaddr($nasIp)) {
1952
		$nasIp = "0.0.0.0";
1953
	}
1954

    
1955
	return $nasIp;
1956
}
1957

    
1958
function portal_ip_from_client_ip($cliip) {
1959
	global $config, $cpzone;
1960

    
1961
	$isipv6 = is_ipaddrv6($cliip);
1962
	$interfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
1963
	foreach ($interfaces as $cpif) {
1964
		if ($isipv6) {
1965
			$ip = get_interface_ipv6($cpif);
1966
			$sn = get_interface_subnetv6($cpif);
1967
		} else {
1968
			$ip = get_interface_ip($cpif);
1969
			$sn = get_interface_subnet($cpif);
1970
		}
1971
		if (ip_in_subnet($cliip, "{$ip}/{$sn}")) {
1972
			return $ip;
1973
		}
1974
	}
1975

    
1976
	$inet = ($isipv6) ? '-inet6' : '-inet';
1977
	$iface = exec_command("/sbin/route -n get {$inet} {$cliip} | /usr/bin/awk '/interface/ { print \$2; };'");
1978
	$iface = trim($iface, "\n");
1979
	if (!empty($iface)) {
1980
		$ip = ($isipv6) ? find_interface_ipv6($iface) : find_interface_ip($iface);
1981
		if (is_ipaddr($ip)) {
1982
			return $ip;
1983
		}
1984
	}
1985

    
1986
	// doesn't match up to any particular interface
1987
	// so let's set the portal IP to what PHP says
1988
	// the server IP issuing the request is.
1989
	// allows same behavior as 1.2.x where IP isn't
1990
	// in the subnet of any CP interface (static routes, etc.)
1991
	// rather than forcing to DNS hostname resolution
1992
	$ip = $_SERVER['SERVER_ADDR'];
1993
	if (is_ipaddr($ip)) {
1994
		return $ip;
1995
	}
1996

    
1997
	return false;
1998
}
1999

    
2000
function portal_hostname_from_client_ip($cliip) {
2001
	global $config, $cpzone;
2002

    
2003
	$cpcfg = $config['captiveportal'][$cpzone];
2004

    
2005
	if (isset($cpcfg['httpslogin'])) {
2006
		$listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 8001);
2007
		$ourhostname = $cpcfg['httpsname'];
2008

    
2009
		if ($listenporthttps != 443) {
2010
			$ourhostname .= ":" . $listenporthttps;
2011
		}
2012
	} else {
2013
		$listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : ($cpcfg['zoneid'] + 8000);
2014
		$ifip = portal_ip_from_client_ip($cliip);
2015
		if (!$ifip) {
2016
			$ourhostname = "{$config['system']['hostname']}.{$config['system']['domain']}";
2017
		} else {
2018
			$ourhostname = (is_ipaddrv6($ifip)) ? "[{$ifip}]" : "{$ifip}";
2019
		}
2020

    
2021
		if ($listenporthttp != 80) {
2022
			$ourhostname .= ":" . $listenporthttp;
2023
		}
2024
	}
2025

    
2026
	return $ourhostname;
2027
}
2028

    
2029
/* functions move from index.php */
2030

    
2031
function portal_reply_page($redirurl, $type = null, $message = null, $clientmac = null, $clientip = null, $username = null, $password = null) {
2032
	global $g, $config, $cpzone;
2033

    
2034
	/* Get captive portal layout */
2035
	if ($type == "redir") {
2036
		header("Location: {$redirurl}");
2037
		return;
2038
	} else if ($type == "login") {
2039
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
2040
	} else {
2041
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
2042
	}
2043

    
2044
	$cpcfg = $config['captiveportal'][$cpzone];
2045

    
2046
	/* substitute the PORTAL_REDIRURL variable */
2047
	if ($cpcfg['preauthurl']) {
2048
		$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
2049
		$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
2050
	}
2051

    
2052
	/* substitute other variables */
2053
	$ourhostname = portal_hostname_from_client_ip($clientip);
2054
	$protocol = (isset($cpcfg['httpslogin'])) ? 'https://' : 'http://';
2055
	$htmltext = str_replace("\$PORTAL_ACTION\$", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
2056
	$htmltext = str_replace("#PORTAL_ACTION#", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
2057

    
2058
	$htmltext = str_replace("\$PORTAL_ZONE\$", htmlspecialchars($cpzone), $htmltext);
2059
	$htmltext = str_replace("\$PORTAL_REDIRURL\$", htmlspecialchars($redirurl), $htmltext);
2060
	$htmltext = str_replace("\$PORTAL_MESSAGE\$", htmlspecialchars($message), $htmltext);
2061
	$htmltext = str_replace("\$CLIENT_MAC\$", htmlspecialchars($clientmac), $htmltext);
2062
	$htmltext = str_replace("\$CLIENT_IP\$", htmlspecialchars($clientip), $htmltext);
2063

    
2064
	// Special handling case for captive portal master page so that it can be ran
2065
	// through the PHP interpreter using the include method above.  We convert the
2066
	// $VARIABLE$ case to #VARIABLE# in /etc/inc/captiveportal.inc before writing out.
2067
	$htmltext = str_replace("#PORTAL_ZONE#", htmlspecialchars($cpzone), $htmltext);
2068
	$htmltext = str_replace("#PORTAL_REDIRURL#", htmlspecialchars($redirurl), $htmltext);
2069
	$htmltext = str_replace("#PORTAL_MESSAGE#", htmlspecialchars($message), $htmltext);
2070
	$htmltext = str_replace("#CLIENT_MAC#", htmlspecialchars($clientmac), $htmltext);
2071
	$htmltext = str_replace("#CLIENT_IP#", htmlspecialchars($clientip), $htmltext);
2072
	$htmltext = str_replace("#USERNAME#", htmlspecialchars($username), $htmltext);
2073
	$htmltext = str_replace("#PASSWORD#", htmlspecialchars($password), $htmltext);
2074

    
2075
	echo $htmltext;
2076
}
2077

    
2078
function portal_mac_radius($clientmac, $clientip) {
2079
	global $config, $cpzone;
2080

    
2081
	$radmac_secret = $config['captiveportal'][$cpzone]['radmac_secret'];
2082

    
2083
	/* authentication against the radius server */
2084
	$username = mac_format($clientmac);
2085
	$auth_list = radius($username, $radmac_secret, $clientip, $clientmac, "MACHINE LOGIN");
2086
	if ($auth_list['auth_val'] == 2) {
2087
		return TRUE;
2088
	}
2089

    
2090
	if (!empty($auth_list['url_redirection'])) {
2091
		portal_reply_page($auth_list['url_redirection'], "redir");
2092
	}
2093

    
2094
	return FALSE;
2095
}
2096

    
2097
function captiveportal_reapply_attributes($cpentry, $attributes) {
2098
	global $config, $cpzone, $g;
2099

    
2100
	if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2101
		$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2102
		$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2103
	} else {
2104
		$dwfaultbw_up = $dwfaultbw_down = 0;
2105
	}
2106
	$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2107
	$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2108
	$bw_up_pipeno = $cpentry[1];
2109
	$bw_down_pipeno = $cpentry[1]+1;
2110

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

    
2115
	unset($bw_up_pipeno, $bw_down_pipeno, $bw_up, $bw_down);
2116
}
2117

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

    
2121
	// Ensure we create an array if we are missing attributes
2122
	if (!is_array($attributes)) {
2123
		$attributes = array();
2124
	}
2125

    
2126
	unset($sessionid);
2127

    
2128
	/* Do not allow concurrent login execution. */
2129
	$cpdblck = lock("captiveportaldb{$cpzone}", LOCK_EX);
2130

    
2131
	if ($attributes['voucher']) {
2132
		$remaining_time = $attributes['session_timeout'];
2133
	// Set RADIUS-Attribute to Voucher to prevent ReAuth-Reqeuest for Vouchers Bug: #2155
2134
		$radiusctx="voucher";
2135
	}
2136

    
2137
	$writecfg = false;
2138
	/* Find an existing session */
2139
	if ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) &&
2140
	    $passthrumac &&
2141
	    isset($config['captiveportal'][$cpzone]['passthrumacadd'])) {
2142
		$mac = captiveportal_passthrumac_findbyname($username);
2143
		if (!empty($mac) && $_POST['replacemacpassthru']) {
2144
			foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $idx => $macent) {
2145
				if ($macent['mac'] != $mac['mac']) {
2146
					continue;
2147
				}
2148

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

    
2178
	/* read in client database */
2179
	$query = "WHERE ip = '{$clientip}'";
2180
	$tmpusername = SQLite3::escapeString(strtolower($username));
2181
	if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
2182
		$query .= " OR (username != 'unauthenticated' AND lower(username) = '{$tmpusername}')";
2183
	}
2184
	$cpdb = captiveportal_read_db($query);
2185

    
2186
	/* Snapshot the timestamp */
2187
	$allow_time = time();
2188
	$radiusservers = captiveportal_get_radius_servers();
2189
	$unsetindexes = array();
2190
	if (is_null($radiusctx)) {
2191
		$radiusctx = 'first';
2192
	}
2193

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

    
2215
			/* This user was already logged in so we disconnect the old one */
2216
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2217
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2218
			$unsetindexes[] = $cpentry[5];
2219
			break;
2220
		} elseif ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && ($username != 'unauthenticated')) {
2221
			/* on the same username */
2222
			if (strcasecmp($cpentry[4], $username) == 0) {
2223
				/* This user was already logged in so we disconnect the old one */
2224
				captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2225
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2226
				$unsetindexes[] = $cpentry[5];
2227
				break;
2228
			}
2229
		}
2230
	}
2231
	unset($cpdb);
2232

    
2233
	if (!empty($unsetindexes)) {
2234
		captiveportal_remove_entries($unsetindexes);
2235
	}
2236

    
2237
	if ($attributes['voucher'] && $remaining_time <= 0) {
2238
		return 0;       // voucher already used and no time left
2239
	}
2240

    
2241
	if (!isset($sessionid)) {
2242
		/* generate unique session ID */
2243
		$tod = gettimeofday();
2244
		$sessionid = substr(md5(mt_rand() . $tod['sec'] . $tod['usec'] . $clientip . $clientmac), 0, 16);
2245

    
2246
		if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2247
			$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2248
			$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2249
		} else {
2250
			$dwfaultbw_up = $dwfaultbw_down = 0;
2251
		}
2252
		$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2253
		$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2254

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

    
2292
			/* if the pool is empty, return appropriate message and exit */
2293
			if (is_null($pipeno)) {
2294
				portal_reply_page($redirurl, "error", "System reached maximum login capacity");
2295
				log_error("Zone: {$cpzone} - WARNING!  Captive portal has reached maximum login capacity");
2296
				unlock($cpdblck);
2297
				return;
2298
			}
2299

    
2300
			$bw_up_pipeno = $pipeno;
2301
			$bw_down_pipeno = $pipeno + 1;
2302
			//$bw_up /= 1000; // Scale to Kbit/s
2303
			$_gb = @pfSense_ipfw_pipe("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2304
			$_gb = @pfSense_ipfw_pipe("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2305

    
2306
			$rule_entry = "{$clientip}/" . (is_ipaddrv6($clientip) ? "128" : "32");
2307
			if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) {
2308
				$rule_entry .= ",{$clientmac}";
2309
			}
2310
			$_gb = @pfSense_ipfw_table("{$cpzone}_auth_up", IP_FW_TABLE_XADD, "{$rule_entry}", $bw_up_pipeno);
2311
			$_gb = @pfSense_ipfw_table("{$cpzone}_auth_down", IP_FW_TABLE_XADD, "{$rule_entry}", $bw_down_pipeno);
2312

    
2313
			if ($attributes['voucher']) {
2314
				$attributes['session_timeout'] = $remaining_time;
2315
			}
2316

    
2317
			/* handle empty attributes */
2318
			$session_timeout = (!empty($attributes['session_timeout'])) ? $attributes['session_timeout'] : 'NULL';
2319
			$idle_timeout = (!empty($attributes['idle_timeout'])) ? $attributes['idle_timeout'] : 'NULL';
2320
			$session_terminate_time = (!empty($attributes['session_terminate_time'])) ? $attributes['session_terminate_time'] : 'NULL';
2321
			$interim_interval = (!empty($attributes['interim_interval'])) ? $attributes['interim_interval'] : 'NULL';
2322

    
2323
			/* escape username */
2324
			$safe_username = SQLite3::escapeString($username);
2325

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

    
2332
			/* store information to database */
2333
			captiveportal_write_db($insertquery);
2334
			unlock($cpdblck);
2335
			unset($insertquery, $bpassword);
2336

    
2337
			if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers[$radiusctx])) {
2338
				$acct_val = RADIUS_ACCOUNTING_START($pipeno, $username, $sessionid, $radiusservers[$radiusctx], $clientip, $clientmac);
2339
				if ($acct_val == 1) {
2340
					captiveportal_logportalauth($username, $clientmac, $clientip, $type, "RADIUS ACCOUNTING FAILED");
2341
				}
2342
			}
2343
		}
2344
	} else {
2345
		/* NOTE: #3062-11 If the pipeno has been allocated free it to not DoS the CP and maintain proper operation as in radius() case */
2346
		if (!is_null($pipeno)) {
2347
			captiveportal_free_dn_ruleno($pipeno);
2348
		}
2349

    
2350
		unlock($cpdblck);
2351
	}
2352

    
2353
	if ($writecfg == true) {
2354
		write_config(gettext("Captive Portal allowed users configuration changed"));
2355
	}
2356

    
2357
	/* redirect user to desired destination */
2358
	if (!empty($attributes['url_redirection'])) {
2359
		$my_redirurl = $attributes['url_redirection'];
2360
	} else if (!empty($redirurl)) {
2361
		$my_redirurl = $redirurl;
2362
	} else if (!empty($config['captiveportal'][$cpzone]['redirurl'])) {
2363
		$my_redirurl = $config['captiveportal'][$cpzone]['redirurl'];
2364
	}
2365

    
2366
	if (isset($config['captiveportal'][$cpzone]['logoutwin_enable']) && !$passthrumac) {
2367
		$ourhostname = portal_hostname_from_client_ip($clientip);
2368
		$protocol = (isset($config['captiveportal'][$cpzone]['httpslogin'])) ? 'https://' : 'http://';
2369
		$logouturl = "{$protocol}{$ourhostname}/";
2370

    
2371
		if (isset($attributes['reply_message'])) {
2372
			$message = $attributes['reply_message'];
2373
		} else {
2374
			$message = 0;
2375
		}
2376

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

    
2379
	} else {
2380
		portal_reply_page($my_redirurl, "redir", "Just redirect the user.");
2381
	}
2382

    
2383
	return $sessionid;
2384
}
2385

    
2386

    
2387
/*
2388
 * Used for when pass-through credits are enabled.
2389
 * Returns true when there was at least one free login to deduct for the MAC.
2390
 * Expired entries are removed as they are seen.
2391
 * Active entries are updated according to the configuration.
2392
 */
2393
function portal_consume_passthrough_credit($clientmac) {
2394
	global $config, $cpzone;
2395

    
2396
	if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count'])) {
2397
		$freeloginscount = $config['captiveportal'][$cpzone]['freelogins_count'];
2398
	} else {
2399
		return false;
2400
	}
2401

    
2402
	if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout'])) {
2403
		$resettimeout = $config['captiveportal'][$cpzone]['freelogins_resettimeout'];
2404
	} else {
2405
		return false;
2406
	}
2407

    
2408
	if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac) {
2409
		return false;
2410
	}
2411

    
2412
	$updatetimeouts = isset($config['captiveportal'][$cpzone]['freelogins_updatetimeouts']);
2413

    
2414
	/*
2415
	 * Read database of used MACs.  Lines are a comma-separated list
2416
	 * of the time, MAC, then the count of pass-through credits remaining.
2417
	 */
2418
	$usedmacs = captiveportal_read_usedmacs_db();
2419

    
2420
	$currenttime = time();
2421
	$found = false;
2422
	foreach ($usedmacs as $key => $usedmac) {
2423
		$usedmac = explode(",", $usedmac);
2424

    
2425
		if ($usedmac[1] == $clientmac) {
2426
			if ($usedmac[0] + ($resettimeout * 3600) > $currenttime) {
2427
				if ($usedmac[2] < 1) {
2428
					if ($updatetimeouts) {
2429
						$usedmac[0] = $currenttime;
2430
						unset($usedmacs[$key]);
2431
						$usedmacs[] = implode(",", $usedmac);
2432
						captiveportal_write_usedmacs_db($usedmacs);
2433
					}
2434

    
2435
					return false;
2436
				} else {
2437
					$usedmac[2] -= 1;
2438
					$usedmacs[$key] = implode(",", $usedmac);
2439
				}
2440

    
2441
				$found = true;
2442
			} else {
2443
				unset($usedmacs[$key]);
2444
			}
2445

    
2446
			break;
2447
		} else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime) {
2448
			unset($usedmacs[$key]);
2449
		}
2450
	}
2451

    
2452
	if (!$found) {
2453
		$usedmac = array($currenttime, $clientmac, $freeloginscount - 1);
2454
		$usedmacs[] = implode(",", $usedmac);
2455
	}
2456

    
2457
	captiveportal_write_usedmacs_db($usedmacs);
2458
	return true;
2459
}
2460

    
2461
function captiveportal_read_usedmacs_db() {
2462
	global $g, $cpzone;
2463

    
2464
	$cpumaclck = lock("captiveusedmacs{$cpzone}");
2465
	if (file_exists("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db")) {
2466
		$usedmacs = file("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2467
		if (!$usedmacs) {
2468
			$usedmacs = array();
2469
		}
2470
	} else {
2471
		$usedmacs = array();
2472
	}
2473

    
2474
	unlock($cpumaclck);
2475
	return $usedmacs;
2476
}
2477

    
2478
function captiveportal_write_usedmacs_db($usedmacs) {
2479
	global $g, $cpzone;
2480

    
2481
	$cpumaclck = lock("captiveusedmacs{$cpzone}", LOCK_EX);
2482
	@file_put_contents("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", implode("\n", $usedmacs));
2483
	unlock($cpumaclck);
2484
}
2485

    
2486
function captiveportal_blocked_mac($mac) {
2487
	global $config, $g, $cpzone;
2488

    
2489
	if (empty($mac) || !is_macaddr($mac)) {
2490
		return false;
2491
	}
2492

    
2493
	if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2494
		return false;
2495
	}
2496

    
2497
	foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) {
2498
		if (($passthrumac['action'] == 'block') &&
2499
		    ($passthrumac['mac'] == strtolower($mac))) {
2500
			return true;
2501
		}
2502
	}
2503

    
2504
	return false;
2505

    
2506
}
2507

    
2508
function captiveportal_send_server_accounting($off = false) {
2509
	global $cpzone, $config;
2510

    
2511
	if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
2512
		return;
2513
	}
2514
	if ($off) {
2515
		$racct = new Auth_RADIUS_Acct_Off;
2516
	} else {
2517
		$racct = new Auth_RADIUS_Acct_On;
2518
	}
2519
	$radiusservers = captiveportal_get_radius_servers();
2520
	if (empty($radiusservers)) {
2521
		return;
2522
	}
2523
	foreach ($radiusservers['first'] as $radsrv) {
2524
		// Add a new server to our instance
2525
		$racct->addServer($radsrv['ipaddr'], $radsrv['acctport'], $radsrv['key']);
2526
	}
2527
	if (PEAR::isError($racct->start())) {
2528
		$retvalue['acct_val'] = 1;
2529
		$retvalue['error'] = $racct->getMessage();
2530

    
2531
		// If we encounter an error immediately stop this function and go back
2532
		$racct->close();
2533
		return $retvalue;
2534
	}
2535
	// Send request
2536
	$result = $racct->send();
2537
	// Evaluation of the response
2538
	// 5 -> Accounting-Response
2539
	// See RFC2866 for this.
2540
	if (PEAR::isError($result)) {
2541
		$retvalue['acct_val'] = 1;
2542
		$retvalue['error'] = $result->getMessage();
2543
	} else if ($result === true) {
2544
		$retvalue['acct_val'] = 5 ;
2545
	} else {
2546
		$retvalue['acct_val'] = 1 ;
2547
	}
2548

    
2549
	$racct->close();
2550
	return $retvalue;
2551
}
2552

    
2553
function captiveportal_isip_logged($clientip) {
2554
	global $g, $cpzone;
2555

    
2556
	/* read in client database */
2557
	$query = "WHERE ip = '{$clientip}'";
2558
	$cpdb = captiveportal_read_db($query);
2559
	foreach ($cpdb as $cpentry) {
2560
		return $cpentry;
2561
	}
2562
}
2563
?>
(5-5/54)