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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
|
<?php
/*
* auth.inc
*
* part of pfSense (https://www.pfsense.org)
* Copyright (c) 2003-2006 Manuel Kasper <mk@neon1.net>
* Copyright (c) 2005-2006 Bill Marquette <bill.marquette@gmail.com>
* Copyright (c) 2006 Paul Taylor <paultaylor@winn-dixie.com>
* Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate)
* 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.
*
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgment:
* "This product includes software developed by the pfSense Project
* for use in the pfSense® software distribution. (http://www.pfsense.org/).
*
* 4. The names "pfSense" and "pfSense Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* coreteam@pfsense.org.
*
* 5. Products derived from this software may not be called "pfSense"
* nor may "pfSense" appear in their names without prior written
* permission of the Electric Sheep Fencing, LLC.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
*
* "This product includes software developed by the pfSense Project
* for use in the pfSense software distribution (http://www.pfsense.org/).
*
* THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 pfSense PROJECT OR
* ITS CONTRIBUTORS 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.
*/
/*
* NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
* file courtesy of Michael Retterklieber.
*/
if (!$do_not_include_config_gui_inc) {
require_once("config.gui.inc");
}
// Will be changed to false if security checks fail
$security_passed = true;
/* If this function doesn't exist, we're being called from Captive Portal or
another internal subsystem which does not include authgui.inc */
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
/* DNS ReBinding attack prevention. https://redmine.pfsense.org/issues/708 */
$found_host = false;
/* Either a IPv6 address with or without a alternate port */
if (strstr($_SERVER['HTTP_HOST'], "]")) {
$http_host_port = explode("]", $_SERVER['HTTP_HOST']);
/* v6 address has more parts, drop the last part */
if (count($http_host_port) > 1) {
array_pop($http_host_port);
$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
} else {
$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
}
} else {
$http_host = explode(":", $_SERVER['HTTP_HOST']);
$http_host = $http_host[0];
}
if (is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") {
$found_host = true;
}
if (strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
strcasecmp($http_host, $config['system']['hostname']) == 0) {
$found_host = true;
}
if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
foreach ($config['dyndnses']['dyndns'] as $dyndns) {
if (strcasecmp($dyndns['host'], $http_host) == 0) {
$found_host = true;
break;
}
}
}
if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
if (strcasecmp($rfc2136['host'], $http_host) == 0) {
$found_host = true;
break;
}
}
}
if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
$althosts = explode(" ", $config['system']['webgui']['althostnames']);
foreach ($althosts as $ah) {
if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
$found_host = true;
break;
}
}
}
if ($found_host == false) {
if (!security_checks_disabled()) {
display_error_form("501", gettext("Potential DNS Rebind attack detected, see http://en.wikipedia.org/wiki/DNS_rebinding<br />Try accessing the router by IP address instead of by hostname."));
exit;
}
$security_passed = false;
}
}
// If the HTTP_REFERER is something other than ourselves then disallow.
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) {
if ($_SERVER['HTTP_REFERER']) {
if (file_exists("{$g['tmp_path']}/setupwizard_lastreferrer")) {
if ($_SERVER['HTTP_REFERER'] == file_get_contents("{$g['tmp_path']}/setupwizard_lastreferrer")) {
unlink("{$g['tmp_path']}/setupwizard_lastreferrer");
header("Refresh: 1; url=index.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="/css/pfSense.css" />
<title><?=gettext("Redirecting..."); ?></title>
</head>
<body id="error" class="no-menu">
<div id="jumbotron">
<div class="container">
<div class="col-sm-offset-3 col-sm-6 col-xs-12">
<p><?=gettext("Redirecting to the dashboard...")?></p>
</div>
</div>
</div>
</body>
</html>
<?php
exit;
}
}
$found_host = false;
$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
$referrer_host = str_replace(array("[", "]"), "", $referrer_host);
if ($referrer_host) {
if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 ||
strcasecmp($referrer_host, $config['system']['hostname']) == 0) {
$found_host = true;
}
if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
$althosts = explode(" ", $config['system']['webgui']['althostnames']);
foreach ($althosts as $ah) {
if (strcasecmp($referrer_host, $ah) == 0) {
$found_host = true;
break;
}
}
}
if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
foreach ($config['dyndnses']['dyndns'] as $dyndns) {
if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
$found_host = true;
break;
}
}
}
if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
$found_host = true;
break;
}
}
}
if (!$found_host) {
$interface_list_ips = get_configured_ip_addresses();
foreach ($interface_list_ips as $ilips) {
if (strcasecmp($referrer_host, $ilips) == 0) {
$found_host = true;
break;
}
}
$interface_list_ipv6s = get_configured_ipv6_addresses(true);
foreach ($interface_list_ipv6s as $ilipv6s) {
$ilipv6s = explode('%', $ilipv6s)[0];
if (strcasecmp($referrer_host, $ilipv6s) == 0) {
$found_host = true;
break;
}
}
if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
// allow SSH port forwarded connections and links from localhost
$found_host = true;
}
}
}
if ($found_host == false) {
if (!security_checks_disabled()) {
display_error_form("501", "An HTTP_REFERER was detected other than what is defined in System -> Advanced (" . htmlspecialchars($_SERVER['HTTP_REFERER']) . "). If not needed, this check can be disabled in System -> Advanced -> Admin.");
exit;
}
$security_passed = false;
}
} else {
$security_passed = false;
}
}
if (function_exists("display_error_form") && $security_passed) {
/* Security checks passed, so it should be OK to turn them back on */
restore_security_checks();
}
unset($security_passed);
$groupindex = index_groups();
$userindex = index_users();
function index_groups() {
global $g, $debug, $config, $groupindex;
$groupindex = array();
if (is_array($config['system']['group'])) {
$i = 0;
foreach ($config['system']['group'] as $groupent) {
$groupindex[$groupent['name']] = $i;
$i++;
}
}
return ($groupindex);
}
function index_users() {
global $g, $debug, $config;
if (is_array($config['system']['user'])) {
$i = 0;
foreach ($config['system']['user'] as $userent) {
$userindex[$userent['name']] = $i;
$i++;
}
}
return ($userindex);
}
function & getUserEntry($name) {
global $debug, $config, $userindex;
$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
if (isset($userindex[$name])) {
return $config['system']['user'][$userindex[$name]];
} elseif ($authcfg['type'] != "Local Database") {
$user = array();
$user['name'] = $name;
return $user;
}
}
function & getUserEntryByUID($uid) {
global $debug, $config;
if (is_array($config['system']['user'])) {
foreach ($config['system']['user'] as & $user) {
if ($user['uid'] == $uid) {
return $user;
}
}
}
return false;
}
function & getGroupEntry($name) {
global $debug, $config, $groupindex;
if (isset($groupindex[$name])) {
return $config['system']['group'][$groupindex[$name]];
}
}
function & getGroupEntryByGID($gid) {
global $debug, $config;
if (is_array($config['system']['group'])) {
foreach ($config['system']['group'] as & $group) {
if ($group['gid'] == $gid) {
return $group;
}
}
}
return false;
}
function get_user_privileges(& $user) {
global $config;
$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
$names = array();
$privs = $user['priv'];
if (!is_array($privs)) {
$privs = array();
}
if ($authcfg['type'] == "ldap") {
$names = @ldap_get_groups($user['name'], $authcfg);
} elseif ($authcfg['type'] == "radius") {
$names = @radius_get_groups($_SESSION['user_radius_attributes']);
}
if (empty($names)) {
$names = local_user_get_groups($user, true);
}
foreach ($names as $name) {
$group = getGroupEntry($name);
if (is_array($group['priv'])) {
$privs = array_merge($privs, $group['priv']);
}
}
return $privs;
}
function userHasPrivilege($userent, $privid = false) {
if (!$privid || !is_array($userent)) {
return false;
}
$privs = get_user_privileges($userent);
if (!is_array($privs)) {
return false;
}
if (!in_array($privid, $privs)) {
return false;
}
return true;
}
function local_backed($username, $passwd) {
$user = getUserEntry($username);
if (!$user) {
return false;
}
if (is_account_disabled($username) || is_account_expired($username)) {
return false;
}
if ($user['bcrypt-hash']) {
if (password_verify($passwd, $user['bcrypt-hash'])) {
return true;
}
}
//for backwards compatibility
if ($user['password']) {
if (crypt($passwd, $user['password']) == $user['password']) {
return true;
}
}
if ($user['md5-hash']) {
if (md5($passwd) == $user['md5-hash']) {
return true;
}
}
return false;
}
function local_sync_accounts() {
global $debug, $config;
conf_mount_rw();
/* remove local users to avoid uid conflicts */
$fd = popen("/usr/sbin/pw usershow -a", "r");
if ($fd) {
while (!feof($fd)) {
$line = explode(":", fgets($fd));
if ($line[0] != "admin") {
if (!strncmp($line[0], "_", 1)) {
continue;
}
if ($line[2] < 2000) {
continue;
}
if ($line[2] > 65000) {
continue;
}
}
/*
* If a crontab was created to user, pw userdel will be interactive and
* can cause issues. Just remove crontab before run it when necessary
*/
unlink_if_exists("/var/cron/tabs/{$line[0]}");
$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($line[0]);
if ($debug) {
log_error(sprintf(gettext("Running: %s"), $cmd));
}
mwexec($cmd);
}
pclose($fd);
}
/* remove local groups to avoid gid conflicts */
$gids = array();
$fd = popen("/usr/sbin/pw groupshow -a", "r");
if ($fd) {
while (!feof($fd)) {
$line = explode(":", fgets($fd));
if (!strncmp($line[0], "_", 1)) {
continue;
}
if ($line[2] < 2000) {
continue;
}
if ($line[2] > 65000) {
continue;
}
$cmd = "/usr/sbin/pw groupdel -g " . escapeshellarg($line[2]);
if ($debug) {
log_error(sprintf(gettext("Running: %s"), $cmd));
}
mwexec($cmd);
}
pclose($fd);
}
/* make sure the all group exists */
$allgrp = getGroupEntryByGID(1998);
local_group_set($allgrp, true);
/* sync all local users */
if (is_array($config['system']['user'])) {
foreach ($config['system']['user'] as $user) {
local_user_set($user);
}
}
/* sync all local groups */
if (is_array($config['system']['group'])) {
foreach ($config['system']['group'] as $group) {
local_group_set($group);
}
}
conf_mount_ro();
}
function local_user_set(& $user) {
global $g, $debug;
if (empty($user['password']) && empty($user['bcrypt-hash'])) {
log_error("There is something wrong in the config because user {$user['name']} password is missing!");
return;
}
conf_mount_rw();
$home_base = "/home/";
$user_uid = $user['uid'];
$user_name = $user['name'];
$user_home = "{$home_base}{$user_name}";
$user_shell = "/etc/rc.initial";
$user_group = "nobody";
// Ensure $home_base exists and is writable
if (!is_dir($home_base)) {
mkdir($home_base, 0755);
}
$lock_account = false;
/* configure shell type */
/* Cases here should be ordered by most privileged to least privileged. */
if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
$user_shell = "/bin/tcsh";
} elseif (userHasPrivilege($user, "user-copy-files")) {
$user_shell = "/usr/local/bin/scponly";
} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
$user_shell = "/sbin/nologin";
} else {
$user_shell = "/sbin/nologin";
$lock_account = true;
}
/* Lock out disabled or expired users, unless it's root/admin. */
if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
$user_shell = "/sbin/nologin";
$lock_account = true;
}
/* root user special handling */
if ($user_uid == 0) {
$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
if ($debug) {
log_error(sprintf(gettext("Running: %s"), $cmd));
}
$fd = popen($cmd, "w");
if (empty($user['bcrypt-hash'])) {
fwrite($fd, $user['password']);
} else {
fwrite($fd, $user['bcrypt-hash']);
}
pclose($fd);
$user_group = "wheel";
$user_home = "/root";
$user_shell = "/etc/rc.initial";
}
/* read from pw db */
$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
$pwread = fgets($fd);
pclose($fd);
$userattrs = explode(":", trim($pwread));
/* determine add or mod */
if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
$user_op = "useradd -m -k /etc/skel -o";
} else {
$user_op = "usermod";
}
$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
/* add or mod pw db */
$cmd = "/usr/sbin/pw {$user_op} -q " .
" -u " . escapeshellarg($user_uid) .
" -n " . escapeshellarg($user_name) .
" -g " . escapeshellarg($user_group) .
" -s " . escapeshellarg($user_shell) .
" -d " . escapeshellarg($user_home) .
" -c " . escapeshellarg($comment) .
" -H 0 2>&1";
if ($debug) {
log_error(sprintf(gettext("Running: %s"), $cmd));
}
$fd = popen($cmd, "w");
if (empty($user['bcrypt-hash'])) {
fwrite($fd, $user['password']);
} else {
fwrite($fd, $user['bcrypt-hash']);
}
pclose($fd);
/* create user directory if required */
if (!is_dir($user_home)) {
mkdir($user_home, 0700);
}
@chown($user_home, $user_name);
@chgrp($user_home, $user_group);
/* write out ssh authorized key file */
if ($user['authorizedkeys']) {
if (!is_dir("{$user_home}/.ssh")) {
@mkdir("{$user_home}/.ssh", 0700);
@chown("{$user_home}/.ssh", $user_name);
}
$keys = base64_decode($user['authorizedkeys']);
@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
@chown("{$user_home}/.ssh/authorized_keys", $user_name);
} else {
unlink_if_exists("{$user_home}/.ssh/authorized_keys");
}
$un = $lock_account ? "" : "un";
exec("/usr/sbin/pw {$un}lock " . escapeshellarg($user_name) . " -q 2>/dev/null");
conf_mount_ro();
}
function local_user_del($user) {
global $debug;
/* remove all memberships */
local_user_set_groups($user);
/* Don't remove /root */
if ($user['uid'] != 0) {
$rmhome = "-r";
}
/* read from pw db */
$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
$pwread = fgets($fd);
pclose($fd);
$userattrs = explode(":", trim($pwread));
if ($userattrs[0] != $user['name']) {
log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
return;
}
/* delete from pw db */
$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($user['name']) . " " . escapeshellarg($rmhome);
if ($debug) {
log_error(sprintf(gettext("Running: %s"), $cmd));
}
mwexec($cmd);
/* Delete user from groups needs a call to write_config() */
local_group_del_user($user);
}
function local_user_set_password(&$user, $password) {
unset($user['password']);
unset($user['md5-hash']);
$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
/* Maintain compatibility with FreeBSD - change $2y$ prefix to $2b$
* https://reviews.freebsd.org/D2742
* XXX: Can be removed as soon as r284483 is MFC'd.
*/
if ($user['bcrypt-hash'][2] == "y") {
$user['bcrypt-hash'][2] = "b";
}
// Converts ascii to unicode.
$astr = (string) $password;
$ustr = '';
for ($i = 0; $i < strlen($astr); $i++) {
$a = ord($astr{$i}) << 8;
$ustr .= sprintf("%X", $a);
}
}
function local_user_get_groups($user, $all = false) {
global $debug, $config;
$groups = array();
if (!is_array($config['system']['group'])) {
return $groups;
}
foreach ($config['system']['group'] as $group) {
if ($all || (!$all && ($group['name'] != "all"))) {
if (is_array($group['member'])) {
if (in_array($user['uid'], $group['member'])) {
$groups[] = $group['name'];
}
}
}
}
if ($all) {
$groups[] = "all";
}
sort($groups);
return $groups;
}
function local_user_set_groups($user, $new_groups = NULL) {
global $debug, $config, $groupindex;
if (!is_array($config['system']['group'])) {
return;
}
$cur_groups = local_user_get_groups($user, true);
$mod_groups = array();
if (!is_array($new_groups)) {
$new_groups = array();
}
if (!is_array($cur_groups)) {
$cur_groups = array();
}
/* determine which memberships to add */
foreach ($new_groups as $groupname) {
if ($groupname == '' || in_array($groupname, $cur_groups)) {
continue;
}
$group = & $config['system']['group'][$groupindex[$groupname]];
$group['member'][] = $user['uid'];
$mod_groups[] = $group;
}
unset($group);
/* determine which memberships to remove */
foreach ($cur_groups as $groupname) {
if (in_array($groupname, $new_groups)) {
continue;
}
if (!isset($config['system']['group'][$groupindex[$groupname]])) {
continue;
}
$group = & $config['system']['group'][$groupindex[$groupname]];
if (is_array($group['member'])) {
$index = array_search($user['uid'], $group['member']);
array_splice($group['member'], $index, 1);
$mod_groups[] = $group;
}
}
unset($group);
/* sync all modified groups */
foreach ($mod_groups as $group) {
local_group_set($group);
}
}
function local_group_del_user($user) {
global $config;
if (!is_array($config['system']['group'])) {
return;
}
foreach ($config['system']['group'] as $group) {
if (is_array($group['member'])) {
foreach ($group['member'] as $idx => $uid) {
if ($user['uid'] == $uid) {
unset($config['system']['group']['member'][$idx]);
}
}
}
}
}
function local_group_set($group, $reset = false) {
global $debug;
$group_name = $group['name'];
$group_gid = $group['gid'];
$group_members = '';
if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
$group_members = implode(",", $group['member']);
}
if (empty($group_name) || $group['scope'] == "remote") {
return;
}
/* determine add or mod */
if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
$group_op = "groupmod -l";
} else {
$group_op = "groupadd -n";
}
/* add or mod group db */
$cmd = "/usr/sbin/pw {$group_op} " .
escapeshellarg($group_name) .
" -g " . escapeshellarg($group_gid) .
" -M " . escapeshellarg($group_members) . " 2>&1";
if ($debug) {
log_error(sprintf(gettext("Running: %s"), $cmd));
}
mwexec($cmd);
}
function local_group_del($group) {
global $debug;
/* delete from group db */
$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
if ($debug) {
log_error(sprintf(gettext("Running: %s"), $cmd));
}
mwexec($cmd);
}
function ldap_test_connection($authcfg) {
global $debug, $config, $g;
if ($authcfg) {
if (strstr($authcfg['ldap_urltype'], "SSL")) {
$ldapproto = "ldaps";
} else {
$ldapproto = "ldap";
}
$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
$ldapport = $authcfg['ldap_port'];
if (!empty($ldapport)) {
$ldapserver .= ":{$ldapport}";
}
$ldapbasedn = $authcfg['ldap_basedn'];
$ldapbindun = $authcfg['ldap_binddn'];
$ldapbindpw = $authcfg['ldap_bindpw'];
} else {
return false;
}
/* first check if there is even an LDAP server populated */
if (!$ldapserver) {
return false;
}
/* Setup CA environment if needed. */
ldap_setup_caenv($authcfg);
/* connect and see if server is up */
$error = false;
if (!($ldap = ldap_connect($ldapserver))) {
$error = true;
}
if ($error == true) {
log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname));
return false;
}
return true;
}
function ldap_setup_caenv($authcfg) {
global $g;
require_once("certs.inc");
unset($caref);
if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
putenv('LDAPTLS_REQCERT=never');
return;
} else {
$caref = lookup_ca($authcfg['ldap_caref']);
if (!$caref) {
log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
putenv('LDAPTLS_REQCERT=hard');
return;
}
if (!is_dir("{$g['varrun_path']}/certs")) {
@mkdir("{$g['varrun_path']}/certs");
}
if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
}
file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", base64_decode($caref['crt']));
@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
putenv('LDAPTLS_REQCERT=hard');
/* XXX: Probably even the hashed link should be created for this? */
putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
}
}
function ldap_test_bind($authcfg) {
global $debug, $config, $g;
if ($authcfg) {
if (strstr($authcfg['ldap_urltype'], "SSL")) {
$ldapproto = "ldaps";
} else {
$ldapproto = "ldap";
}
$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
$ldapport = $authcfg['ldap_port'];
if (!empty($ldapport)) {
$ldapserver .= ":{$ldapport}";
}
$ldapbasedn = $authcfg['ldap_basedn'];
$ldapbindun = $authcfg['ldap_binddn'];
$ldapbindpw = $authcfg['ldap_bindpw'];
$ldapver = $authcfg['ldap_protver'];
$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
if (empty($ldapbndun) || empty($ldapbindpw)) {
$ldapanon = true;
} else {
$ldapanon = false;
}
} else {
return false;
}
/* first check if there is even an LDAP server populated */
if (!$ldapserver) {
return false;
}
/* Setup CA environment if needed. */
ldap_setup_caenv($authcfg);
/* connect and see if server is up */
$error = false;
if (!($ldap = ldap_connect($ldapserver))) {
$error = true;
}
if ($error == true) {
log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname));
return false;
}
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
if (!(ldap_start_tls($ldap))) {
log_error(sprintf(gettext("ERROR! ldap_test_bind() could not STARTTLS to server %s."), $ldapname));
@ldap_close($ldap);
return false;
}
}
$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
if ($ldapanon == true) {
if (!($res = @ldap_bind($ldap))) {
@ldap_close($ldap);
return false;
}
} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
@ldap_close($ldap);
return false;
}
@ldap_unbind($ldap);
return true;
}
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
global $debug, $config, $g;
if (!function_exists("ldap_connect")) {
return;
}
$ous = array();
if ($authcfg) {
if (strstr($authcfg['ldap_urltype'], "SSL")) {
$ldapproto = "ldaps";
} else {
$ldapproto = "ldap";
}
$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
$ldapport = $authcfg['ldap_port'];
if (!empty($ldapport)) {
$ldapserver .= ":{$ldapport}";
}
$ldapbasedn = $authcfg['ldap_basedn'];
$ldapbindun = $authcfg['ldap_binddn'];
$ldapbindpw = $authcfg['ldap_bindpw'];
$ldapver = $authcfg['ldap_protver'];
if (empty($ldapbindun) || empty($ldapbindpw)) {
$ldapanon = true;
} else {
$ldapanon = false;
}
$ldapname = $authcfg['name'];
$ldapfallback = false;
$ldapscope = $authcfg['ldap_scope'];
$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
} else {
return false;
}
/* first check if there is even an LDAP server populated */
if (!$ldapserver) {
log_error(gettext("ERROR! ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
return $ous;
}
/* Setup CA environment if needed. */
ldap_setup_caenv($authcfg);
/* connect and see if server is up */
$error = false;
if (!($ldap = ldap_connect($ldapserver))) {
$error = true;
}
if ($error == true) {
log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname));
return $ous;
}
$ldapfilter = "(|(ou=*)(cn=Users))";
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
if (!(ldap_start_tls($ldap))) {
log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
@ldap_close($ldap);
return false;
}
}
$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
if ($ldapanon == true) {
if (!($res = @ldap_bind($ldap))) {
log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
@ldap_close($ldap);
return $ous;
}
} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
@ldap_close($ldap);
return $ous;
}
if ($ldapscope == "one") {
$ldapfunc = "ldap_list";
} else {
$ldapfunc = "ldap_search";
}
$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
$info = @ldap_get_entries($ldap, $search);
if (is_array($info)) {
foreach ($info as $inf) {
if (!$show_complete_ou) {
$inf_split = explode(",", $inf['dn']);
$ou = $inf_split[0];
$ou = str_replace("OU=", "", $ou);
$ou = str_replace("CN=", "", $ou);
} else {
if ($inf['dn']) {
$ou = $inf['dn'];
}
}
if ($ou) {
$ous[] = $ou;
}
}
}
@ldap_unbind($ldap);
return $ous;
}
function ldap_get_groups($username, $authcfg) {
global $debug, $config;
if (!function_exists("ldap_connect")) {
return;
}
if (!$username) {
return false;
}
if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
$username_split = explode("@", $username);
$username = $username_split[0];
}
if (stristr($username, "\\")) {
$username_split = explode("\\", $username);
$username = $username_split[0];
}
//log_error("Getting LDAP groups for {$username}.");
if ($authcfg) {
if (strstr($authcfg['ldap_urltype'], "SSL")) {
$ldapproto = "ldaps";
} else {
$ldapproto = "ldap";
}
$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
$ldapport = $authcfg['ldap_port'];
if (!empty($ldapport)) {
$ldapserver .= ":{$ldapport}";
}
$ldapbasedn = $authcfg['ldap_basedn'];
$ldapbindun = $authcfg['ldap_binddn'];
$ldapbindpw = $authcfg['ldap_bindpw'];
$ldapauthcont = $authcfg['ldap_authcn'];
$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
if (isset($authcfg['ldap_rfc2307'])) {
$ldapfilter = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
} else {
$ldapfilter = "({$ldapnameattribute}={$username})";
}
$ldaptype = "";
$ldapver = $authcfg['ldap_protver'];
if (empty($ldapbindun) || empty($ldapbindpw)) {
$ldapanon = true;
} else {
$ldapanon = false;
}
$ldapname = $authcfg['name'];
$ldapfallback = false;
$ldapscope = $authcfg['ldap_scope'];
$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
} else {
return false;
}
if (isset($authcfg['ldap_rfc2307'])) {
$ldapdn = $ldapbasedn;
} else {
$ldapdn = $_SESSION['ldapdn'];
}
/*Convert attribute to lowercase. php ldap arrays put everything in lowercase */
$ldapgroupattribute = strtolower($ldapgroupattribute);
$memberof = array();
/* Setup CA environment if needed. */
ldap_setup_caenv($authcfg);
/* connect and see if server is up */
$error = false;
if (!($ldap = ldap_connect($ldapserver))) {
$error = true;
}
if ($error == true) {
log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
return memberof;
}
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
if (!(ldap_start_tls($ldap))) {
log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
@ldap_close($ldap);
return false;
}
}
/* bind as user that has rights to read group attributes */
$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
if ($ldapanon == true) {
if (!($res = @ldap_bind($ldap))) {
log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
@ldap_close($ldap);
return false;
}
} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
@ldap_close($ldap);
return memberof;
}
/* get groups from DN found */
/* use ldap_read instead of search so we don't have to do a bunch of extra work */
/* since we know the DN is in $_SESSION['ldapdn'] */
//$search = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
if ($ldapscope == "one") {
$ldapfunc = "ldap_list";
} else {
$ldapfunc = "ldap_search";
}
$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
$info = @ldap_get_entries($ldap, $search);
$gresults = isset($authcfg['ldap_rfc2307']) ? $info : $info[0][$ldapgroupattribute];
if (is_array($gresults)) {
/* Iterate through the groups and throw them into an array */
foreach ($gresults as $grp) {
if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
}
}
}
/* Time to close LDAP connection */
@ldap_unbind($ldap);
$groups = print_r($memberof, true);
//log_error("Returning groups ".$groups." for user $username");
return $memberof;
}
function ldap_format_host($host) {
return is_ipaddrv6($host) ? "[$host]" : $host ;
}
function ldap_backed($username, $passwd, $authcfg) {
global $debug, $config;
if (!$username) {
return;
}
if (!function_exists("ldap_connect")) {
return;
}
if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
$username_split = explode("@", $username);
$username = $username_split[0];
}
if (stristr($username, "\\")) {
$username_split = explode("\\", $username);
$username = $username_split[0];
}
if ($authcfg) {
if (strstr($authcfg['ldap_urltype'], "SSL")) {
$ldapproto = "ldaps";
} else {
$ldapproto = "ldap";
}
$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
$ldapport = $authcfg['ldap_port'];
if (!empty($ldapport)) {
$ldapserver .= ":{$ldapport}";
}
$ldapbasedn = $authcfg['ldap_basedn'];
$ldapbindun = $authcfg['ldap_binddn'];
$ldapbindpw = $authcfg['ldap_bindpw'];
if (empty($ldapbindun) || empty($ldapbindpw)) {
$ldapanon = true;
} else {
$ldapanon = false;
}
$ldapauthcont = $authcfg['ldap_authcn'];
$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
$ldapextendedquery = $authcfg['ldap_extended_query'];
$ldapfilter = "";
if (!$ldapextendedqueryenabled) {
$ldapfilter = "({$ldapnameattribute}={$username})";
} else {
$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
}
$ldaptype = "";
$ldapver = $authcfg['ldap_protver'];
$ldapname = $authcfg['name'];
$ldapscope = $authcfg['ldap_scope'];
$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
} else {
return false;
}
/* first check if there is even an LDAP server populated */
if (!$ldapserver) {
if ($ldapfallback) {
log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined. Defaulting to local user database. Visit System -> User Manager."));
return local_backed($username, $passwd);
} else {
log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined."));
}
return false;
}
/* Setup CA environment if needed. */
ldap_setup_caenv($authcfg);
/* Make sure we can connect to LDAP */
$error = false;
if (!($ldap = ldap_connect($ldapserver))) {
$error = true;
}
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
if (!(ldap_start_tls($ldap))) {
log_error(sprintf(gettext("ERROR! ldap_backed() could not STARTTLS to server %s."), $ldapname));
@ldap_close($ldap);
return false;
}
}
if ($error == true) {
log_error(sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname));
return false;
}
/* ok, its up. now, lets bind as the bind user so we can search it */
$error = false;
$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
if ($ldapanon == true) {
if (!($res = @ldap_bind($ldap))) {
$error = true;
}
} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
$error = true;
}
if ($error == true) {
@ldap_close($ldap);
log_error(sprintf(gettext("ERROR! Could not bind to server %s."), $ldapname));
return false;
}
/* Get LDAP Authcontainers and split em up. */
$ldac_splits = explode(";", $ldapauthcont);
/* setup the usercount so we think we haven't found anyone yet */
$usercount = 0;
/*****************************************************************/
/* We first find the user based on username and filter */
/* then, once we find the first occurrence of that person */
/* we set session variables to point to the OU and DN of the */
/* person. To later be used by ldap_get_groups. */
/* that way we don't have to search twice. */
/*****************************************************************/
if ($debug) {
log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
}
/* Iterate through the user containers for search */
foreach ($ldac_splits as $i => $ldac_split) {
$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
/* Make sure we just use the first user we find */
if ($debug) {
log_auth(sprintf(gettext('Now Searching in server %1$s, container %2$s with filter %3$s.'), $ldapname, utf8_decode($ldac_split), utf8_decode($ldapfilter)));
}
if ($ldapscope == "one") {
$ldapfunc = "ldap_list";
} else {
$ldapfunc = "ldap_search";
}
/* Support legacy auth container specification. */
if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
$search = @$ldapfunc($ldap, $ldac_split, $ldapfilter);
} else {
$search = @$ldapfunc($ldap, $ldapsearchbasedn, $ldapfilter);
}
if (!$search) {
log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
continue;
}
$info = ldap_get_entries($ldap, $search);
$matches = $info['count'];
if ($matches == 1) {
$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
$_SESSION['ldapou'] = $ldac_split[$i];
$_SESSION['ldapon'] = "true";
$usercount = 1;
break;
}
}
if ($usercount != 1) {
@ldap_unbind($ldap);
log_error(gettext("ERROR! Either LDAP search failed, or multiple users were found."));
return false;
}
/* Now lets bind as the user we found */
$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
@ldap_unbind($ldap);
return false;
}
if ($debug) {
$userdn = isset($authcfg['ldap_utf8']) ? utf8_decode($userdn) : $userdn;
log_auth(sprintf(gettext('Logged in successfully as %1$s via LDAP server %2$s with DN = %3$s.'), $username, $ldapname, $userdn));
}
/* At this point we are bound to LDAP so the user was auth'd okay. Close connection. */
@ldap_unbind($ldap);
return true;
}
function radius_backed($username, $passwd, $authcfg, &$attributes = array()) {
global $debug, $config;
$ret = false;
require_once("radius.inc");
$rauth = new Auth_RADIUS_PAP($username, $passwd);
if ($authcfg) {
$radiusservers = array();
$radiusservers[0]['ipaddr'] = $authcfg['host'];
$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
} else {
return false;
}
/* Add new servers to our instance */
foreach ($radiusservers as $radsrv) {
$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
}
if (PEAR::isError($rauth->start())) {
$retvalue['auth_val'] = 1;
$retvalue['error'] = $rauth->getError();
if ($debug) {
printf(gettext("RADIUS start: %s<br />\n"), $retvalue['error']);
}
}
// XXX - billm - somewhere in here we need to handle securid challenge/response
/* Send request */
$result = $rauth->send();
if (PEAR::isError($result)) {
$retvalue['auth_val'] = 1;
$retvalue['error'] = $result->getMessage();
if ($debug) {
printf(gettext("RADIUS send failed: %s<br />\n"), $retvalue['error']);
}
} else if ($result === true) {
if ($rauth->getAttributes()) {
$attributes = $rauth->listAttributes();
}
$retvalue['auth_val'] = 2;
if ($debug) {
printf(gettext("RADIUS Auth succeeded")."<br />\n");
}
$ret = true;
} else {
$retvalue['auth_val'] = 3;
if ($debug) {
printf(gettext("RADIUS Auth rejected")."<br />\n");
}
}
// close OO RADIUS_AUTHENTICATION
$rauth->close();
return $ret;
}
/*
$attributes must contain a "class" key containing the groups and local
groups must exist to match.
*/
function radius_get_groups($attributes) {
$groups = array();
if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
/* Some RADIUS servers return multiple class attributes, so check them all. */
$groups = array();
if (!empty($attributes['class']) && is_array($attributes['class'])) {
foreach ($attributes['class'] as $class) {
$groups = array_unique(array_merge($groups, explode(";", $class)));
}
}
foreach ($groups as & $grp) {
$grp = trim($grp);
if (strtolower(substr($grp, 0, 3)) == "ou=") {
$grp = substr($grp, 3);
}
}
}
return $groups;
}
function get_user_expiration_date($username) {
$user = getUserEntry($username);
if ($user['expires']) {
return $user['expires'];
}
}
function is_account_expired($username) {
$expirydate = get_user_expiration_date($username);
if ($expirydate) {
if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
return true;
}
}
return false;
}
function is_account_disabled($username) {
$user = getUserEntry($username);
if (isset($user['disabled'])) {
return true;
}
return false;
}
function get_user_settings($username) {
global $config;
$settings = array();
$settings['widgets'] = $config['widgets'];
$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
$user = getUserEntry($username);
if (isset($user['customsettings'])) {
$settings['customsettings'] = true;
if (isset($user['widgets'])) {
// This includes the 'sequence', and any widgetname-config per-widget settings.
$settings['widgets'] = $user['widgets'];
}
if (isset($user['dashboardcolumns'])) {
$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
}
if (isset($user['webguicss'])) {
$settings['webgui']['webguicss'] = $user['webguicss'];
}
if (isset($user['webguihostnamemenu'])) {
$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
}
$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
} else {
$settings['customsettings'] = false;
}
if ($settings['webgui']['dashboardcolumns'] < 1) {
$settings['webgui']['dashboardcolumns'] = 2;
}
return $settings;
}
function save_widget_settings($username, $settings, $message = "") {
global $config, $userindex;
$user = getUserEntry($username);
if (strlen($message) > 0) {
$msgout = $message;
} else {
$msgout = gettext("Widget configuration has been changed.");
}
if (isset($user['customsettings'])) {
$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
} else {
$config['widgets'] = $settings;
write_config($msgout);
}
}
function auth_get_authserver($name) {
global $config;
if (is_array($config['system']['authserver'])) {
foreach ($config['system']['authserver'] as $authcfg) {
if ($authcfg['name'] == $name) {
return $authcfg;
}
}
}
if ($name == "Local Database") {
return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
}
}
function auth_get_authserver_list() {
global $config;
$list = array();
if (is_array($config['system']['authserver'])) {
foreach ($config['system']['authserver'] as $authcfg) {
/* Add support for disabled entries? */
$list[$authcfg['name']] = $authcfg;
}
}
$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
return $list;
}
function getUserGroups($username, $authcfg, &$attributes = array()) {
global $config;
$allowed_groups = array();
switch ($authcfg['type']) {
case 'ldap':
$allowed_groups = @ldap_get_groups($username, $authcfg);
break;
case 'radius':
$allowed_groups = @radius_get_groups($attributes);
break;
default:
$user = getUserEntry($username);
$allowed_groups = @local_user_get_groups($user, true);
break;
}
$member_groups = array();
if (is_array($config['system']['group'])) {
foreach ($config['system']['group'] as $group) {
if (in_array($group['name'], $allowed_groups)) {
$member_groups[] = $group['name'];
}
}
}
return $member_groups;
}
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
if (is_array($username) || is_array($password)) {
return false;
}
if (!$authcfg) {
return local_backed($username, $password);
}
$authenticated = false;
switch ($authcfg['type']) {
case 'ldap':
if (ldap_backed($username, $password, $authcfg)) {
$authenticated = true;
}
break;
case 'radius':
if (radius_backed($username, $password, $authcfg, $attributes)) {
$authenticated = true;
}
break;
default:
/* lookup user object by name */
if (local_backed($username, $password)) {
$authenticated = true;
}
break;
}
return $authenticated;
}
function session_auth() {
global $config, $_SESSION, $page;
// Handle HTTPS httponly and secure flags
$currentCookieParams = session_get_cookie_params();
session_set_cookie_params(
$currentCookieParams["lifetime"],
$currentCookieParams["path"],
NULL,
($config['system']['webgui']['protocol'] == "https"),
true
);
if (!session_id()) {
session_start();
}
// Detect protocol change
if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
return false;
}
/* Validate incoming login request */
$attributes = array();
if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
// Generate a new id to avoid session fixation
session_regenerate_id();
$_SESSION['Logged_In'] = "True";
$_SESSION['remoteauth'] = $remoteauth;
$_SESSION['Username'] = $_POST['usernamefld'];
$_SESSION['user_radius_attributes'] = $attributes;
$_SESSION['last_access'] = time();
$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
if (!isset($config['system']['webgui']['quietlogin'])) {
log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR']));
}
if (isset($_POST['postafterlogin'])) {
return true;
} else {
if (empty($page)) {
$page = "/";
}
header("Location: {$page}");
}
exit;
} else {
/* give the user an error message */
$_SESSION['Login_Error'] = "Username or Password incorrect";
log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
if (isAjax()) {
echo "showajaxmessage('{$_SESSION['Login_Error']}');";
return;
}
}
}
/* Show login page if they aren't logged in */
if (empty($_SESSION['Logged_In'])) {
return false;
}
/* If session timeout isn't set, we don't mark sessions stale */
if (!isset($config['system']['webgui']['session_timeout'])) {
/* Default to 4 hour timeout if one is not set */
if ($_SESSION['last_access'] < (time() - 14400)) {
$_GET['logout'] = true;
$_SESSION['Logout'] = true;
} else {
$_SESSION['last_access'] = time();
}
} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
/* only update if it wasn't ajax */
if (!isAjax()) {
$_SESSION['last_access'] = time();
}
} else {
/* Check for stale session */
if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
$_GET['logout'] = true;
$_SESSION['Logout'] = true;
} else {
/* only update if it wasn't ajax */
if (!isAjax()) {
$_SESSION['last_access'] = time();
}
}
}
/* user hit the logout button */
if (isset($_GET['logout'])) {
if ($_SESSION['Logout']) {
log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
} else {
log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
}
/* wipe out $_SESSION */
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
/* and destroy it */
session_destroy();
$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
$scriptElms = count($scriptName);
$scriptName = $scriptName[$scriptElms-1];
if (isAjax()) {
return false;
}
/* redirect to page the user is on, it'll prompt them to login again */
header("Location: {$scriptName}");
return false;
}
/*
* this is for debugging purpose if you do not want to use Ajax
* to submit a HTML form. It basically disables the observation
* of the submit event and hence does not trigger Ajax.
*/
if ($_GET['disable_ajax']) {
$_SESSION['NO_AJAX'] = "True";
}
/*
* Same to re-enable Ajax.
*/
if ($_GET['enable_ajax']) {
unset($_SESSION['NO_AJAX']);
}
return true;
}
?>
|