forked from pfsense/pfsense
/
captiveportal.inc
2082 lines (1779 loc) · 69.8 KB
/
captiveportal.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
captiveportal.inc
part of pfSense (http://www.pfSense.org)
Copyright (C) 2004-2011 Scott Ullrich <sullrich@gmail.com>
Copyright (C) 2009-2012 Ermal Luçi <eri@pfsense.org>
Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>.
originally part of m0n0wall (http://m0n0.ch/wall)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
This version of captiveportal.inc has been modified by Rob Parker
<rob.parker@keycom.co.uk> to include changes for per-user bandwidth management
via returned RADIUS attributes. This page has been modified to delete any
added rules which may have been created by other per-user code (index.php, etc).
These changes are (c) 2004 Keycom PLC.
pfSense_BUILDER_BINARIES: /sbin/ipfw /sbin/sysctl
pfSense_BUILDER_BINARIES: /usr/local/sbin/lighttpd /usr/local/bin/minicron /sbin/pfctl
pfSense_BUILDER_BINARIES: /bin/hostname /bin/cp
pfSense_MODULE: captiveportal
*/
/* include all configuration functions */
require_once("config.inc");
require_once("functions.inc");
require_once("filter.inc");
require_once("radius.inc");
require_once("voucher.inc");
function get_default_captive_portal_html() {
global $config, $g, $cpzone;
$htmltext = <<<EOD
<html>
<body>
<form method="post" action="\$PORTAL_ACTION\$">
<input name="redirurl" type="hidden" value="\$PORTAL_REDIRURL\$">
<input name="zone" type="hidden" value="\$PORTAL_ZONE\$">
<center>
<table cellpadding="6" cellspacing="0" width="550" height="380" style="border:1px solid #000000">
<tr height="10" bgcolor="#990000">
<td style="border-bottom:1px solid #000000">
<font color='white'>
<b>
{$g['product_name']} captive portal
</b>
</font>
</td>
</tr>
<tr>
<td>
<div id="mainlevel">
<center>
<table width="100%" border="0" cellpadding="5" cellspacing="0">
<tr>
<td>
<center>
<div id="mainarea">
<center>
<table width="100%" border="0" cellpadding="5" cellspacing="5">
<tr>
<td>
<div id="maindivarea">
<center>
<div id='statusbox'>
<font color='red' face='arial' size='+1'>
<b>
\$PORTAL_MESSAGE\$
</b>
</font>
</div>
<br/>
<div id='loginbox'>
<table>
<tr><td colspan="2"><center>Welcome to the {$g['product_name']} Captive Portal!</td></tr>
<tr><td> </td></tr>
<tr><td align="right">Username:</td><td><input name="auth_user" type="text" style="border: 1px dashed;"></td></tr>
<tr><td align="right">Password:</td><td><input name="auth_pass" type="password" style="border: 1px dashed;"></td></tr>
<tr><td> </td></tr>
EOD;
if(isset($config['voucher'][$cpzone]['enable'])) {
$htmltext .= <<<EOD
<tr>
<td align="right">Enter Voucher Code: </td>
<td><input name="auth_voucher" type="text" style="border:1px dashed;" size="22"></td>
</tr>
EOD;
}
$htmltext .= <<<EOD
<tr>
<td colspan="2"><center><input name="accept" type="submit" value="Continue"></center></td>
</tr>
</table>
</div>
</center>
</div>
</td>
</tr>
</table>
</center>
</div>
</center>
</td>
</tr>
</table>
</center>
</div>
</td>
</tr>
</table>
</center>
</form>
</body>
</html>
EOD;
return $htmltext;
}
function captiveportal_load_modules() {
global $config;
mute_kernel_msgs();
if (!is_module_loaded("ipfw.ko")) {
mwexec("/sbin/kldload ipfw");
/* make sure ipfw is not on pfil hooks */
mwexec("/sbin/sysctl net.inet.ip.pfil.inbound=\"pf\" net.inet6.ip6.pfil.inbound=\"pf\"" .
" net.inet.ip.pfil.outbound=\"pf\" net.inet6.ip6.pfil.outbound=\"pf\"");
/* Activate layer2 filtering */
mwexec("/sbin/sysctl net.link.ether.ipfw=1 net.inet.ip.fw.one_pass=1");
}
/* Always load dummynet now that even allowed ip and mac passthrough use it. */
if (!is_module_loaded("dummynet.ko")) {
mwexec("/sbin/kldload dummynet");
mwexec("/sbin/sysctl net.inet.ip.dummynet.io_fast=1 net.inet.ip.dummynet.hash_size=256");
}
unmute_kernel_msgs();
/* XXX: This are not used in pfSense, if needed can be tuned
if($config['system']['maximumstates'] <> "" && is_numeric($config['system']['maximumstates'])) {
mwexec("sysctl net.inet.ip.fw.dyn_max={$config['system']['maximumstates']}");
} else {
mwexec("sysctl net.inet.ip.fw.dyn_max=10000");
}
*/
}
function captiveportal_configure() {
global $config, $cpzone;
if (is_array($config['captiveportal'])) {
foreach ($config['captiveportal'] as $cpkey => $cp) {
$cpzone = $cpkey;
captiveportal_configure_zone($cp);
}
} else
mwexec("/sbin/sysctl net.link.ether.ipfw=0");
}
function captiveportal_configure_zone($cpcfg) {
global $config, $g, $cpzone;
$captiveportallck = lock("captiveportal{$cpzone}", LOCK_EX);
if (isset($cpcfg['enable'])) {
if ($g['booting']) {
echo "Starting captive portal({$cpcfg['zone']})... ";
/* remove old information */
unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
} else
captiveportal_syslog("Reconfiguring captive portal({$cpcfg['zone']}).");
/* init ipfw rules */
captiveportal_init_rules(true);
/* kill any running minicron */
killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
/* initialize minicron interval value */
$croninterval = $cpcfg['croninterval'] ? $cpcfg['croninterval'] : 60;
/* double check if the $croninterval is numeric and at least 10 seconds. If not we set it to 60 to avoid problems */
if ((!is_numeric($croninterval)) || ($croninterval < 10))
$croninterval = 60;
/* write portal page */
if (is_array($cpcfg['page']) && $cpcfg['page']['htmltext'])
$htmltext = base64_decode($cpcfg['page']['htmltext']);
else {
/* example/template page */
$htmltext = get_default_captive_portal_html();
}
$fd = @fopen("{$g['varetc_path']}/captiveportal_{$cpzone}.html", "w");
if ($fd) {
// Special case handling. Convert so that we can pass this page
// through the PHP interpreter later without clobbering the vars.
$htmltext = str_replace("\$PORTAL_ZONE\$", "#PORTAL_ZONE#", $htmltext);
$htmltext = str_replace("\$PORTAL_REDIRURL\$", "#PORTAL_REDIRURL#", $htmltext);
$htmltext = str_replace("\$PORTAL_MESSAGE\$", "#PORTAL_MESSAGE#", $htmltext);
$htmltext = str_replace("\$CLIENT_MAC\$", "#CLIENT_MAC#", $htmltext);
$htmltext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $htmltext);
$htmltext = str_replace("\$ORIGINAL_PORTAL_IP\$", "#ORIGINAL_PORTAL_IP#", $htmltext);
$htmltext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $htmltext);
if($cpcfg['preauthurl']) {
$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
}
fwrite($fd, $htmltext);
fclose($fd);
}
unset($htmltext);
/* write error page */
if (is_array($cpcfg['page']) && $cpcfg['page']['errtext'])
$errtext = base64_decode($cpcfg['page']['errtext']);
else {
/* example page */
$errtext = get_default_captive_portal_html();
}
$fd = @fopen("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html", "w");
if ($fd) {
// Special case handling. Convert so that we can pass this page
// through the PHP interpreter later without clobbering the vars.
$errtext = str_replace("\$PORTAL_ZONE\$", "#PORTAL_ZONE#", $errtext);
$errtext = str_replace("\$PORTAL_REDIRURL\$", "#PORTAL_REDIRURL#", $errtext);
$errtext = str_replace("\$PORTAL_MESSAGE\$", "#PORTAL_MESSAGE#", $errtext);
$errtext = str_replace("\$CLIENT_MAC\$", "#CLIENT_MAC#", $errtext);
$errtext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $errtext);
$errtext = str_replace("\$ORIGINAL_PORTAL_IP\$", "#ORIGINAL_PORTAL_IP#", $errtext);
$errtext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $errtext);
if($cpcfg['preauthurl']) {
$errtext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $errtext);
$errtext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $errtext);
}
fwrite($fd, $errtext);
fclose($fd);
}
unset($errtext);
/* write logout page */
if (is_array($cpcfg['page']) && $cpcfg['page']['logouttext'])
$logouttext = base64_decode($cpcfg['page']['logouttext']);
else {
/* example page */
$logouttext = <<<EOD
<HTML>
<HEAD><TITLE>Redirecting...</TITLE></HEAD>
<BODY>
<SPAN STYLE="font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">
<B>Redirecting to <A HREF="<?=\$my_redirurl;?>"><?=\$my_redirurl;?></A>...</B>
</SPAN>
<SCRIPT LANGUAGE="JavaScript">
<!--
LogoutWin = window.open('', 'Logout', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=256,height=64');
if (LogoutWin) {
LogoutWin.document.write('<HTML>');
LogoutWin.document.write('<HEAD><TITLE>Logout</TITLE></HEAD>') ;
LogoutWin.document.write('<BODY BGCOLOR="#435370">');
LogoutWin.document.write('<DIV ALIGN="center" STYLE="color: #ffffff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">') ;
LogoutWin.document.write('<B>Click the button below to disconnect</B><P>');
LogoutWin.document.write('<FORM METHOD="POST" ACTION="<?=\$logouturl;?>">');
LogoutWin.document.write('<INPUT NAME="logout_id" TYPE="hidden" VALUE="<?=\$sessionid;?>">');
LogoutWin.document.write('<INPUT NAME="zone" TYPE="hidden" VALUE="<?=\$cpzone;?>">');
LogoutWin.document.write('<INPUT NAME="logout" TYPE="submit" VALUE="Logout">');
LogoutWin.document.write('</FORM>');
LogoutWin.document.write('</DIV></BODY>');
LogoutWin.document.write('</HTML>');
LogoutWin.document.close();
}
document.location.href="<?=\$my_redirurl;?>";
-->
</SCRIPT>
</BODY>
</HTML>
EOD;
}
$fd = @fopen("{$g['varetc_path']}/captiveportal-{$cpzone}-logout.html", "w");
if ($fd) {
fwrite($fd, $logouttext);
fclose($fd);
}
unset($logouttext);
/* write elements */
captiveportal_write_elements();
/* kill any running mini_httpd */
killbypid("{$g['varrun_path']}/lighty-{$cpzone}-CaptivePortal.pid");
killbypid("{$g['varrun_path']}/lighty-{$cpzone}-CaptivePortal-SSL.pid");
/* start up the webserving daemon */
captiveportal_init_webgui_zone($cpcfg);
/* Kill any existing prunecaptiveportal processes */
if (file_exists("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid"))
killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
/* start pruning process (interval defaults to 60 seconds) */
mwexec("/usr/local/bin/minicron $croninterval {$g['varrun_path']}/cp_prunedb_{$cpzone}.pid " .
"/etc/rc.prunecaptiveportal {$cpzone}");
/* generate radius server database */
unlink_if_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db");
captiveportal_init_radius_servers();
if ($g['booting']) {
/* send Accounting-On to server */
captiveportal_send_server_accounting();
echo "done\n";
}
} else {
killbypid("{$g['varrun_path']}/lighty-{$cpzone}-CaptivePortal.pid");
killbypid("{$g['varrun_path']}/lighty-{$cpzone}-CaptivePortal-SSL.pid");
killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
@unlink("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
@unlink("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
@unlink("{$g['varetc_path']}/captiveportal-{$cpzone}-logout.html");
captiveportal_radius_stop_all();
/* send Accounting-Off to server */
if (!$g['booting']) {
captiveportal_send_server_accounting(true);
}
/* remove old information */
unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
unlink_if_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db");
mwexec("/usr/local/sbin/ipfw_context -d {$cpzone}", true);
if (empty($config['captiveportal']))
mwexec("/sbin/sysctl net.link.ether.ipfw=0");
else {
/* Deactivate ipfw(4) if not needed */
$cpactive = false;
foreach ($config['captiveportal'] as $cpkey => $cp) {
if (isset($cp['enable'])) {
$cpactive = true;
break;
}
}
if ($cpactive === false)
mwexec("/sbin/sysctl net.link.ether.ipfw=0");
}
}
unlock($captiveportallck);
return 0;
}
function captiveportal_init_webgui() {
global $config, $cpzone;
if (is_array($config['captiveportal'])) {
foreach ($config['captiveportal'] as $cpkey => $cp) {
$cpzone = $cpkey;
captiveportal_init_webgui_zone($cp);
}
}
}
function captiveportal_init_webgui_zonename($zone) {
global $config, $cpzone;
if (isset($config['captiveportal'][$zone])) {
$cpzone = $zone;
captiveportal_init_webgui_zone($config['captiveportal'][$zone]);
}
}
function captiveportal_init_webgui_zone($cpcfg) {
global $g, $config, $cpzone;
if (!isset($cpcfg['enable']))
return;
if (isset($cpcfg['httpslogin'])) {
$cert = lookup_cert($cpcfg['certref']);
$crt = base64_decode($cert['crt']);
$key = base64_decode($cert['prv']);
$ca = ca_chain($cert);
/* generate lighttpd configuration */
$listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 1);
system_generate_lighty_config("{$g['varetc_path']}/lighty-{$cpzone}-CaptivePortal-SSL.conf",
$crt, $key, $ca, "lighty-{$cpzone}-CaptivePortal-SSL.pid", $listenporthttps, "/usr/local/captiveportal",
"cert-{$cpzone}-portal.pem", "ca-{$cpzone}-portal.pem", $cpzone);
}
/* generate lighttpd configuration */
$listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : $cpcfg['zoneid'];
system_generate_lighty_config("{$g['varetc_path']}/lighty-{$cpzone}-CaptivePortal.conf",
"", "", "", "lighty-{$cpzone}-CaptivePortal.pid", $listenporthttp, "/usr/local/captiveportal",
"", "", $cpzone);
@unlink("{$g['varrun']}/lighty-{$cpzone}-CaptivePortal.pid");
/* attempt to start lighttpd */
$res = mwexec("/usr/local/sbin/lighttpd -f {$g['varetc_path']}/lighty-{$cpzone}-CaptivePortal.conf");
/* fire up https instance */
if (isset($cpcfg['httpslogin'])) {
@unlink("{$g['varrun']}/lighty-{$cpzone}-CaptivePortal-SSL.pid");
$res = mwexec("/usr/local/sbin/lighttpd -f {$g['varetc_path']}/lighty-{$cpzone}-CaptivePortal-SSL.conf");
}
}
/* reinit will disconnect all users, be careful! */
function captiveportal_init_rules($reinit = false) {
global $config, $g, $cpzone;
if (!isset($config['captiveportal'][$cpzone]['enable']))
return;
captiveportal_load_modules();
mwexec("/usr/local/sbin/ipfw_context -a {$cpzone}", true);
$cpips = array();
$ifaces = get_configured_interface_list();
$cpinterfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
$firsttime = 0;
foreach ($cpinterfaces as $cpifgrp) {
if (!isset($ifaces[$cpifgrp]))
continue;
$tmpif = get_real_interface($cpifgrp);
if (!empty($tmpif)) {
$cpipm = get_interface_ip($cpifgrp);
if (is_ipaddr($cpipm)) {
$carpif = link_ip_to_carp_interface($cpipm);
if (!empty($carpif)) {
$carpsif = explode(" ", $carpif);
foreach ($carpsif as $cpcarp) {
mwexec("/usr/local/sbin/ipfw_context -a {$cpzone} -n {$cpcarp}", true);
$carpip = find_interface_ip($cpcarp);
if (is_ipaddr($carpip))
$cpips[] = $carpip;
}
}
$cpips[] = $cpipm;
}
mwexec("/usr/local/sbin/ipfw_context -a {$cpzone} -n {$tmpif}", true);
}
}
if (count($cpips) > 0) {
$cpactive = true;
} else
return false;
if ($reinit == false)
$captiveportallck = lock("captiveportal{$cpzone}");
$cprules = "add 65291 allow pfsync from any to any\n";
$cprules .= "add 65292 allow carp from any to any\n";
$cprules .= <<<EOD
# layer 2: pass ARP
add 65301 pass layer2 mac-type arp,rarp
# pfsense requires for WPA
add 65302 pass layer2 mac-type 0x888e,0x88c7
# PPP Over Ethernet Session Stage/Discovery Stage
add 65303 pass layer2 mac-type 0x8863,0x8864
# layer 2: block anything else non-IP(v4/v6)
add 65307 deny layer2 not mac-type ip,ipv6
EOD;
$rulenum = 65310;
$ipcount = 0;
$ips = "";
foreach ($cpips as $cpip) {
if($ipcount == 0) {
$ips = "{$cpip} ";
} else {
$ips .= "or {$cpip} ";
}
$ipcount++;
}
$ips = "{ 255.255.255.255 or {$ips} }";
$cprules .= "add {$rulenum} pass ip from any to {$ips} in\n";
$rulenum++;
$cprules .= "add {$rulenum} pass ip from {$ips} to any out\n";
$rulenum++;
$cprules .= "add {$rulenum} pass icmp from {$ips} to any out icmptype 0\n";
$rulenum++;
$cprules .= "add {$rulenum} pass icmp from any to {$ips} in icmptype 8 \n";
$rulenum++;
/* Allowed ips */
$cprules .= "add {$rulenum} pipe tablearg ip from table(3) to any in\n";
$rulenum++;
$cprules .= "add {$rulenum} pipe tablearg ip from any to table(4) out\n";
$rulenum++;
/* Authenticated users rules. */
$cprules .= "add {$rulenum} pipe tablearg ip from table(1) to any in\n";
$rulenum++;
$cprules .= "add {$rulenum} pipe tablearg ip from any to table(2) out\n";
$rulenum++;
$listenporthttp =
$config['captiveportal'][$cpzone]['listenporthttp'] ?
$config['captiveportal'][$cpzone]['listenporthttp'] :
$config['captiveportal'][$cpzone]['zoneid'];
if (isset($config['captiveportal'][$cpzone]['httpslogin'])) {
$listenporthttps = $listenporthttp + 1;
$cprules .= "add 65531 fwd 127.0.0.1,{$listenporthttps} tcp from any to any dst-port 443 in\n";
}
$cprules .= <<<EOD
# redirect non-authenticated clients to captive portal
add 65532 fwd 127.0.0.1,{$listenporthttp} tcp from any to any dst-port 80 in
# let the responses from the captive portal web server back out
add 65533 pass tcp from any to any out
# block everything else
add 65534 deny all from any to any
EOD;
/* generate passthru mac database */
$cprules .= captiveportal_passthrumac_configure(true);
$cprules .= "\n";
/* allowed ipfw rules to make allowed ip work */
$cprules .= captiveportal_allowedip_configure();
/* allowed ipfw rules to make allowed hostnames work */
$cprules .= captiveportal_allowedhostname_configure();
/* load rules */
$cprules = "flush\n{$cprules}";
file_put_contents("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules", $cprules);
mwexec("/sbin/ipfw -x {$cpzone} -q {$g['tmp_path']}/ipfw_{$cpzone}.cp.rules", true);
//@unlink("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules");
unset($cprules, $tmprules);
if ($reinit == false)
unlock($captiveportallck);
}
/*
* Remove clients that have been around for longer than the specified amount of time
* db file structure:
* timestamp,ipfw_rule_no,clientip,clientmac,username,sessionid,password,session_timeout,idle_timeout,session_terminate_time,interim_interval
* (password is in Base64 and only saved when reauthentication is enabled)
*/
function captiveportal_prune_old() {
global $g, $config, $cpzone;
if (empty($cpzone))
return;
$cpcfg = $config['captiveportal'][$cpzone];
$vcpcfg = $config['voucher'][$cpzone];
/* check for expired entries */
$idletimeout = 0;
$timeout = 0;
if (!empty($cpcfg['timeout']) && is_numeric($cpcfg['timeout']))
$timeout = $cpcfg['timeout'] * 60;
if (!empty($cpcfg['idletimeout']) && is_numeric($cpcfg['idletimeout']))
$idletimeout = $cpcfg['idletimeout'] * 60;
/* Is there any job to do? */
if (!$timeout && !$idletimeout && !isset($cpcfg['reauthenticate']) &&
!isset($cpcfg['radiussession_timeout']) && !isset($vcpcfg['enable']))
return;
$radiussrvs = captiveportal_get_radius_servers();
/* Read database */
/* NOTE: while this can be simplified in non radius case keep as is for now */
$cpdb = captiveportal_read_db();
/*
* To make sure we iterate over ALL accounts on every run the count($cpdb) is moved
* outside of the loop. Otherwise the loop would evaluate count() on every iteration
* and since $i would increase and count() would decrement they would meet before we
* had a chance to iterate over all accounts.
*/
$unsetindexes = array();
$voucher_needs_sync = false;
/*
* Snapshot the time here to use for calculation to speed up the process.
* If something is missed next run will catch it!
*/
$pruning_time = time();
$stop_time = $pruning_time;
foreach ($cpdb as $cpentry) {
$timedout = false;
$term_cause = 1;
if (empty($cpentry[10]))
$cpentry[10] = 'first';
$radiusservers = $radiussrvs[$cpentry[10]];
/* hard timeout? */
if ($timeout) {
if (($pruning_time - $cpentry[0]) >= $timeout) {
$timedout = true;
$term_cause = 5; // Session-Timeout
}
}
/* Session-Terminate-Time */
if (!$timedout && !empty($cpentry[9])) {
if ($pruning_time >= $cpentry[9]) {
$timedout = true;
$term_cause = 5; // Session-Timeout
}
}
/* check if the radius idle_timeout attribute has been set and if its set change the idletimeout to this value */
$uidletimeout = (is_numeric($cpentry[8])) ? $cpentry[8] : $idletimeout;
/* if an idle timeout is specified, get last activity timestamp from ipfw */
if (!$timedout && $uidletimeout > 0) {
$lastact = captiveportal_get_last_activity($cpentry[2]);
/* If the user has logged on but not sent any traffic they will never be logged out.
* We "fix" this by setting lastact to the login timestamp.
*/
$lastact = $lastact ? $lastact : $cpentry[0];
if ($lastact && (($pruning_time - $lastact) >= $uidletimeout)) {
$timedout = true;
$term_cause = 4; // Idle-Timeout
$stop_time = $lastact; // Entry added to comply with WISPr
}
}
/* if vouchers are configured, activate session timeouts */
if (!$timedout && isset($vcpcfg['enable']) && !empty($cpentry[7])) {
if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
$timedout = true;
$term_cause = 5; // Session-Timeout
$voucher_needs_sync = true;
}
}
/* if radius session_timeout is enabled and the session_timeout is not null, then check if the user should be logged out */
if (!$timedout && isset($cpcfg['radiussession_timeout']) && !empty($cpentry[7])) {
if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
$timedout = true;
$term_cause = 5; // Session-Timeout
}
}
if ($timedout) {
captiveportal_disconnect($cpentry, $radiusservers,$term_cause,$stop_time);
captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "TIMEOUT");
$unsetindexes[] = $cpentry[5];
}
/* do periodic RADIUS reauthentication? */
if (!$timedout && !empty($radiusservers)) {
if (isset($cpcfg['radacct_enable'])) {
if ($cpcfg['reauthenticateacct'] == "stopstart") {
/* stop and restart accounting */
RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
$cpentry[4], // username
$cpentry[5], // sessionid
$cpentry[0], // start time
$radiusservers,
$cpentry[2], // clientip
$cpentry[3], // clientmac
10); // NAS Request
pfSense_ipfw_Tableaction($cpzone, IP_FW_TABLE_ZERO_ENTRY_STATS, 1, $cpentry[2]);
pfSense_ipfw_Tableaction($cpzone, IP_FW_TABLE_ZERO_ENTRY_STATS, 2, $cpentry[2]);
RADIUS_ACCOUNTING_START($cpentry[1], // ruleno
$cpentry[4], // username
$cpentry[5], // sessionid
$radiusservers,
$cpentry[2], // clientip
$cpentry[3]); // clientmac
} else if ($cpcfg['reauthenticateacct'] == "interimupdate") {
$session_time = $pruning_time - $cpentry[0];
if (!empty($cpentry[10]) && $cpentry[10] > 60)
$interval = $cpentry[10];
else
$interval = 0;
$past_interval_min = ($session_time > $interval);
$within_interval = ($session_time % $interval >= 0 && $session_time % $interval <= 59);
if (($interval > 0 && $past_interval_min && $within_interval) || $interval === 0) {
RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
$cpentry[4], // username
$cpentry[5], // sessionid
$cpentry[0], // start time
$radiusservers,
$cpentry[2], // clientip
$cpentry[3], // clientmac
10, // NAS Request
true); // Interim Updates
}
}
}
/* check this user against RADIUS again */
if (isset($cpcfg['reauthenticate'])) {
$auth_list = RADIUS_AUTHENTICATION($cpentry[4], // username
base64_decode($cpentry[6]), // password
$radiusservers,
$cpentry[2], // clientip
$cpentry[3], // clientmac
$cpentry[1]); // ruleno
if ($auth_list['auth_val'] == 3) {
captiveportal_disconnect($cpentry, $radiusservers, 17);
captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "RADIUS_DISCONNECT", $auth_list['reply_message']);
$unsetindexes[] = $cpentry[5];
} else if ($auth_list['auth_val'] == 2)
captiveportal_reapply_attributes($cpentry, $auth_list);
}
}
}
unset($cpdb);
captiveportal_prune_old_automac();
if ($voucher_needs_sync == true)
/* Triger a sync of the vouchers on config */
send_event("service sync vouchers");
/* write database */
if (!empty($unsetindexes))
captiveportal_remove_entries($unsetindexes);
}
function captiveportal_prune_old_automac() {
global $g, $config, $cpzone;
if (is_array($config['captiveportal'][$cpzone]['passthrumac']) && isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
$tmpvoucherdb = array();
$macrules = "";
$writecfg = false;
foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $eid => $emac) {
if ($emac['logintype'] == "voucher") {
if (isset($tmpvoucherdb[$emac['username']])) {
$temac = $config['captiveportal'][$cpzone]['passthrumac'][$tmpvoucherdb[$emac['username']]];
$ruleno = captiveportal_get_ipfw_passthru_ruleno($temac['mac']);
$pipeno = captiveportal_get_dn_passthru_ruleno($temac['mac']);
if ($ruleno) {
captiveportal_free_ipfw_ruleno($ruleno);
$macrules .= "delete {$ruleno}";
++$ruleno;
$macrules .= "delete {$ruleno}";
}
if ($pipeno) {
captiveportal_free_dn_ruleno($pipeno);
$macrules .= "pipe delete {$pipeno}\n";
++$pipeno;
$macrules .= "pipe delete {$pipeno}\n";
}
$writecfg = true;
captiveportal_logportalauth($temac['username'], $temac['mac'], $temac['ip'], "DUPLICATE {$temac['username']} LOGIN - TERMINATING OLD SESSION");
unset($config['captiveportal'][$cpzone]['passthrumac'][$tmpvoucherdb[$emac['username']]]);
}
$tmpvoucherdb[$emac['username']] = $eid;
if (voucher_auth($emac['username']) <= 0) {
$ruleno = captiveportal_get_ipfw_passthru_ruleno($emac['mac']);
$pipeno = captiveportal_get_dn_passthru_ruleno($emac['mac']);
if ($ruleno) {
captiveportal_free_ipfw_ruleno($ruleno);
$macrules .= "delete {$ruleno}";
++$ruleno;
$macrules .= "delete {$ruleno}";
}
if ($pipeno) {
captiveportal_free_dn_ruleno($pipeno);
$macrules .= "pipe delete {$pipeno}\n";
++$pipeno;
$macrules .= "pipe delete {$pipeno}\n";
}
$writecfg = true;
captiveportal_logportalauth($emac['username'], $emac['mac'], $emac['ip'], "EXPIRED {$emac['username']} LOGIN - TERMINATING SESSION");
unset($config['captiveportal'][$cpzone]['passthrumac'][$eid]);
}
}
}
if (!empty($macrules)) {
@file_put_contents("{$g['tmp_path']}/macentry.prunerules.tmp", $macrules);
unset($macrules);
mwexec("/sbin/ipfw -x {$cpzone} -q {$g['tmp_path']}/macentry.prunerules.tmp");
}
if ($writecfg === true)
write_config("Prune session for auto-added macs");
}
}
/* remove a single client according to the DB entry */
function captiveportal_disconnect($dbent, $radiusservers,$term_cause = 1,$stop_time = null) {
global $g, $config, $cpzone;
$stop_time = (empty($stop_time)) ? time() : $stop_time;
/* this client needs to be deleted - remove ipfw rules */
if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers)) {
RADIUS_ACCOUNTING_STOP($dbent[1], // ruleno
$dbent[4], // username
$dbent[5], // sessionid
$dbent[0], // start time
$radiusservers,
$dbent[2], // clientip
$dbent[3], // clientmac
$term_cause, // Acct-Terminate-Cause
false,
$stop_time);
}
if (is_ipaddr($dbent[2])) {
/* Delete client's ip entry from tables 1 and 2. */
pfSense_ipfw_Tableaction($cpzone, IP_FW_TABLE_DEL, 1, $dbent[2]);
pfSense_ipfw_Tableaction($cpzone, IP_FW_TABLE_DEL, 2, $dbent[2]);
/* XXX: Redundant?! Ensure all pf(4) states are killed. */
pfSense_kill_states($dbent[2]);
pfSense_kill_srcstates($dbent[2]);
}
/*
* These are the pipe numbers we use to control traffic shaping for each logged in user via captive portal
* We could get an error if the pipe doesn't exist but everything should still be fine
*/
if (!empty($dbent[1])) {
pfSense_pipe_action("pipe delete {$dbent[1]}");
pfSense_pipe_action("pipe delete " . ($dbent[1]+1));
/* Release the ruleno so it can be reallocated to new clients. */
captiveportal_free_dn_ruleno($dbent[1]);
}
// XMLRPC Call over to the master Voucher node
if(!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) {
$syncip = $config['voucher'][$cpzone]['vouchersyncdbip'];
$syncport = $config['voucher'][$cpzone]['vouchersyncport'];
$syncpass = $config['voucher'][$cpzone]['vouchersyncpass'];
$vouchersyncusername = $config['voucher'][$cpzone]['vouchersyncusername'];
$remote_status = xmlrpc_sync_voucher_disconnect($dbent, $syncip, $syncport, $syncpass, $vouchersyncusername, $term_cause, $stop_time);
}
}
/* remove a single client by sessionid */
function captiveportal_disconnect_client($sessionid, $term_cause = 1, $logoutReason = "LOGOUT") {
global $g, $config;
$radiusservers = captiveportal_get_radius_servers();
/* read database */
$result = captiveportal_read_db("WHERE sessionid = '{$sessionid}'");
/* find entry */
if (!empty($result)) {
captiveportal_write_db("DELETE FROM captiveportal WHERE sessionid = '{$sessionid}'");
foreach ($result as $cpentry) {
if (empty($cpentry[10]))
$cpentry[10] = 'first';
captiveportal_disconnect($cpentry, $radiusservers[$cpentry[10]], $term_cause);
captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "DISCONNECT");
}
unset($result);
}
}
/* send RADIUS acct stop for all current clients */
function captiveportal_radius_stop_all() {
global $config, $cpzone;
if (!isset($config['captiveportal'][$cpzone]['radacct_enable']))
return;
$radiusservers = captiveportal_get_radius_servers();
if (!empty($radiusservers)) {
$cpdb = captiveportal_read_db();
foreach ($cpdb as $cpentry) {
if (empty($cpentry[10]))
$cpentry[10] = 'first';
if (!empty($radiusservers[$cpentry[10]])) {
RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
$cpentry[4], // username
$cpentry[5], // sessionid
$cpentry[0], // start time
$radiusservers[$cpentry[10]],
$cpentry[2], // clientip
$cpentry[3], // clientmac
7); // Admin Reboot
}
}
}
}
function captiveportal_passthrumac_configure_entry($macent) {
$bwUp = empty($macent['bw_up']) ? 0 : $macent['bw_up'];
$bwDown = empty($macent['bw_down']) ? 0 : $macent['bw_down'];
$ruleno = captiveportal_get_next_ipfw_ruleno();
$pipeno = captiveportal_get_next_dn_ruleno();
$rules = "";
$pipeup = $pipeno;
pfSense_pipe_action("pipe {$pipeup} config bw {$bwUp}Kbit/s queue 100 buckets 16");
$pipedown = $pipeno + 1;
pfSense_pipe_action("pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16");
$rules .= "add {$ruleno} pipe {$pipeup} ip from any to any MAC {$macent['mac']} any\n";
$ruleno++;
$rules .= "add {$ruleno} pipe {$pipedown} ip from any to any MAC any {$macent['mac']}\n";
return $rules;
}
function captiveportal_passthrumac_configure($lock = false) {
global $config, $g, $cpzone;
$rules = "";
if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
$macdb = array();
foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
$rules .= captiveportal_passthrumac_configure_entry($macent);
$macdb[$macent['mac']][$cpzone]['active'] = true;
}
}
return $rules;
}
function captiveportal_passthrumac_findbyname($username) {
global $config, $cpzone;
if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
if ($macent['username'] == $username)
return $macent;
}
}
return NULL;
}
/*
* table (3=IN)/(4=OUT) hold allowed ip's without bw limits
*/
function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) {
global $g;
/* Instead of copying this entire function for something
* easy such as hostname vs ip address add this check
*/
if ($ishostname === true) {
if (!$g['booting']) {
$ipaddress = gethostbyname($ipent['hostname']);
if (!is_ipaddr($ipaddress))
return;
}
} else
$ipaddress = $ipent['ip'];
$rules = "";
$cp_filterdns_conf = "";
$enBwup = empty($ipent['bw_up']) ? 0 : intval($ipent['bw_up']);
$enBwdown = empty($ipent['bw_down']) ? 0 : intval($ipent['bw_down']);
$pipeno = captiveportal_get_next_dn_ruleno();