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
|
<?php
/****h* pfSense/config
* NAME
* config.inc - Functions to manipulate config.xml
* DESCRIPTION
* This include contains various config.xml specific functions.
* HISTORY
* $Id$
******
config.inc
Copyright (C) 2004-2006 Scott Ullrich
All rights reserved.
originally part of m0n0wall (http://m0n0.ch/wall)
Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
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.
*/
/*
* XXX: Hack around the cvs syntax checks.
* DISABLE_PHP_LINT_CHECKING
*/
if($g['booting']) echo ".";
/* do not load this file twice. */
if($config_inc_loaded == true)
return;
else
$config_inc_loaded = true;
// Set the memory limit to 128M. When someone has something like 500+ tunnels
// the parser needs quite a bit of ram. Do not remove this line unless you
// know what you are doing. If in doubt, check with dev@ _/FIRST/_!
ini_set("memory_limit","128M");
/* include globals from notices.inc /utility/XML parser files */
require_once("notices.inc");
if($g['booting']) echo ".";
require_once("util.inc");
if($g['booting']) echo ".";
require_once("xmlparse.inc");
if($g['booting']) echo ".";
require_once("crypt.inc");
/* read platform */
if($g['booting']) echo ".";
if (file_exists("{$g['etc_path']}/platform")) {
$g['platform'] = chop(file_get_contents("{$g['etc_path']}/platform"));
} else {
$g['platform'] = "unknown";
}
/* if /debugging exists, lets set $debugging
so we can output more information */
if(file_exists("/debugging")) {
$debugging = true;
$g['debug'] = true;
}
if($g['booting']) echo ".";
if(file_exists("/cf/conf/config.xml")) {
$config_contents = file_get_contents("/cf/conf/config.xml");
if(stristr($config_contents, "<m0n0wall>") == true) {
if($g['booting']) echo ".";
/* user has just upgraded to m0n0wall, replace root xml tags */
log_error("Upgrading m0n0wall configuration to pfSense... ");
$config_contents = str_replace("m0n0wall","pfsense", $config_contents);
if (!config_validate("{$g['conf_path']}/config.xml"))
log_error("ERROR! Could not convert m0n0wall -> pfsense in config.xml");
conf_mount_rw();
$fd = fopen("/cf/conf/config.xml", "w");
fwrite($fd, $config_contents);
fclose($fd);
conf_mount_ro();
}
}
/* if our config file exists bail out, we're already set. */
if ($g['booting'] and !file_exists($g['cf_conf_path'] . "/config.xml") ) {
if($g['booting']) echo ".";
/* find the device where config.xml resides and write out an fstab */
unset($cfgdevice);
if($g['booting']) echo ".";
/* check if there's already an fstab (NFS booting?) */
if (!file_exists("{$g['etc_path']}/fstab")) {
if($g['booting']) echo ".";
if (strstr($g['platform'], "cdrom")) {
/* config is on floppy disk for CD-ROM version */
$cfgdevice = $cfgpartition = "fd0";
$dmesg = `dmesg -a`;
if(ereg("da0", $dmesg) == true) {
$cfgdevice = $cfgpartition = "da0" ;
if (mwexec("/sbin/mount -r /dev/{$cfgdevice} /cf")) {
/* could not mount, fallback to floppy */
$cfgdevice = $cfgpartition = "fd0";
}
}
$cfgfstype = "msdosfs";
echo "CDROM build\n";
echo " CFG: {$cfgpartition}\n";
echo " TYPE: {$cfgfstype}\n";
} else {
if($g['booting']) echo ".";
/* probe kernel known disks until we find one with config.xml */
$disks = explode(" ", trim(preg_replace("/kern.disks: /", "", exec("/sbin/sysctl kern.disks"))));
foreach ($disks as $mountdisk) {
/* skip mfs mounted filesystems */
if (strstr($mountdisk, "md"))
continue;
if (mwexec("/sbin/mount -r /dev/{$mountdisk}a {$g['cf_path']}") == 0) {
if (file_exists("{$g['cf_conf_path']}/config.xml")) {
/* found it */
$cfgdevice = $mountdisk;
$cfgpartition = $cfgdevice . "a";
$cfgfstype = "ufs";
echo "Found configuration on $cfgdevice.\n";
}
mwexec("/sbin/umount -f {$g['cf_path']}");
if ($cfgdevice)
break;
}
if (mwexec("/sbin/mount -r /dev/{$mountdisk}d {$g['cf_path']}") == 0) {
if($g['booting']) echo ".";
if (file_exists("{$g['cf_conf_path']}/config.xml")) {
/* found it */
$cfgdevice = $mountdisk;
$cfgpartition = $cfgdevice . "d";
$cfgfstype = "ufs";
echo "Found configuration on $cfgdevice.\n";
}
mwexec("/sbin/umount -f {$g['cf_path']}");
if ($cfgdevice)
break;
}
}
}
if($g['booting']) echo ".";
if (!$cfgdevice) {
$last_backup = discover_last_backup();
if($last_backup) {
log_error("No config.xml found, attempting last known config restore.");
file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
restore_backup("/cf/conf/backup/{$last_backup}");
} else {
log_error("No config.xml or config backups found, resetting to factory defaults.");
restore_backup('/conf.default/config.xml');
}
}
/* write device name to a file for rc.firmware */
$fd = fopen("{$g['varetc_path']}/cfdevice", "w");
fwrite($fd, $cfgdevice . "\n");
fclose($fd);
/* write out an fstab */
$fd = fopen("{$g['etc_path']}/fstab", "w");
$fstab = "/dev/{$cfgpartition} {$g['cf_path']} {$cfgfstype} ro 1 1\n";
$fstab .= "proc /proc procfs rw 0 0\n";
fwrite($fd, $fstab);
fclose($fd);
}
if($g['booting']) echo ".";
/* mount all filesystems */
mwexec("/sbin/mount -a");
}
/****f* config/encrypted_configxml
* NAME
* encrypted_configxml - Checks to see if config.xml is encrypted and if so, prompts to unlock.
* INPUTS
* None
* RESULT
* $config - rewrites config.xml without encryption
******/
function encrypted_configxml() {
global $g, $config;
if(file_exists($g['conf_path'] . "/config.xml")) {
if($g['booting']) {
$configtxt = file_get_contents($g['conf_path'] . "/config.xml");
if(tagfile_deformat($configtxt, $configtxt, "config.xml")) {
$fp = fopen('php://stdin', 'r');
$data = "";
echo "\n\n*** Encrypted config.xml detected ***\n";
while($data == "") {
echo "\nEnter the password to decrypt config.xml: ";
$decrypt_password = chop(fgets($fp));
$data = decrypt_data($configtxt, $decrypt_password);
if(!strstr($data, "<pfsense>"))
$data = "";
if($data) {
$fd = fopen($g['conf_path'] . "/config.xml", "w");
fwrite($fd, $data);
fclose($fd);
echo "\nConfig.xml unlocked.\n";
fclose($fp);
} else {
echo "\nInvalid password entered. Please try again.\n";
}
}
}
}
}
}
/****f* config/parse_config
* NAME
* parse_config - Read in config.cache or config.xml if needed and return $config array
* INPUTS
* $parse - boolean to force parse_config() to read config.xml and generate config.cache
* RESULT
* $config - array containing all configuration variables
******/
function parse_config($parse = false) {
global $g, $config_parsed;
$lockkey = lock('config');
$config_parsed == false;
if (!file_exists("{$g['conf_path']}/config.xml") || filesize("{$g['conf_path']}/config.xml") == 0) {
$last_backup = discover_last_backup();
if($last_backup) {
log_error("No config.xml found, attempting last known config restore.");
file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
restore_backup("{$g['conf_path']}/backup/{$last_backup}");
} else {
unlock($lockkey);
die("Config.xml is corrupted and is 0 bytes. Could not restore a previous backup.");
}
}
if($g['booting']) echo ".";
// Check for encrypted config.xml
encrypted_configxml();
if(!$parse) {
if(file_exists($g['tmp_path'] . '/config.cache')) {
$config = unserialize(file_get_contents($g['tmp_path'] . '/config.cache'));
if(is_null($config)) {
unlock($lockkey);
parse_config(true);
$lockkey = lock('config');
}
} else {
if(!file_exists($g['conf_path'] . "/config.xml")) {
log_error("No config.xml found, attempting last known config restore.");
file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
$last_backup = discover_last_backup();
if ($last_backup)
restore_backup("/cf/conf/backup/{$last_backup}");
else
log_error("Could not restore config.xml.");
}
unlock($lockkey);
$config = parse_config(true);
$lockkey = lock('config');
}
} else {
if(!file_exists($g['conf_path'] . "/config.xml")) {
if($g['booting']) echo ".";
log_error("No config.xml found, attempting last known config restore.");
file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
$last_backup = discover_last_backup();
if ($last_backup)
restore_backup("/cf/conf/backup/{$last_backup}");
else
log_error("Could not restore config.xml.");
}
$config = parse_xml_config($g['conf_path'] . '/config.xml', $g['xml_rootobj']);
if($config == "-1") {
$last_backup = discover_last_backup();
if ($last_backup)
restore_backup("/cf/conf/backup/{$last_backup}");
else
log_error(gettext("Could not restore config.xml."));
}
generate_config_cache($config);
}
if($g['booting']) echo ".";
alias_make_table($config);
$config_parsed = true;
unlock($lockkey);
return $config;
}
/****f* config/generate_config_cache
* NAME
* generate_config_cache - Write serialized configuration to cache.
* INPUTS
* $config - array containing current firewall configuration
* RESULT
* boolean - true on completion
******/
function generate_config_cache($config) {
global $g;
$configcache = fopen($g['tmp_path'] . '/config.cache', "w");
fwrite($configcache, serialize($config));
fclose($configcache);
}
function discover_last_backup() {
$backups = split("\n", `cd /cf/conf/backup && ls -ltr *.xml | awk '{print \$9}'`);
$last_backup = "";
foreach($backups as $backup)
if($backup)
$last_backup = $backup;
return $last_backup;
}
function restore_backup($file) {
global $g;
if (file_exists($file)) {
conf_mount_rw();
copy("$file","/cf/conf/config.xml");
unlink_if_exists("{$g['tmp_path']}/config.cache");
log_error("{$g['product_name']} is restoring the configuration $file");
file_notice("config.xml", "{$g['product_name']} is restoring the configuration $file", "pfSenseConfigurator", "");
conf_mount_ro();
}
}
/****f* config/parse_config_bootup
* NAME
* parse_config_bootup - Bootup-specific configuration checks.
* RESULT
* null
******/
function parse_config_bootup() {
global $config, $g, $noparseconfig;
if($g['booting']) echo ".";
$lockkey = lock('config');
if (!$noparseconfig) {
if (!file_exists("{$g['conf_path']}/config.xml")) {
if ($g['booting']) {
if (strstr($g['platform'], "cdrom")) {
/* try copying the default config. to the floppy */
echo "Resetting factory defaults...\n";
reset_factory_defaults(true);
if (file_exists("{$g['conf_path']}/config.xml")) {
/* do nothing, we have a file. */
} else {
echo "No XML configuration file found - using factory defaults.\n";
echo "Make sure that the configuration floppy disk with the conf/config.xml\n";
echo "file is inserted. If it isn't, your configuration changes will be lost\n";
echo "on reboot.\n";
}
} else {
$last_backup = discover_last_backup();
if($last_backup) {
log_error("No config.xml found, attempting last known config restore.");
file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
restore_backup("/cf/conf/backup/{$last_backup}");
}
if(!file_exists("{$g['conf_path']}/config.xml")) {
echo "XML configuration file not found. {$g['product_name']} cannot continue booting.\n";
mwexec("/sbin/halt");
exit;
}
log_error("Last known config found and restored. Please double check your configuration file for accuracy.");
file_notice("config.xml", "Last known config found and restored. Please double check your configuration file for accuracy.", "pfSenseConfigurator", "");
}
} else {
unlock($lockkey);
exit(0);
}
}
}
if (filesize("{$g['conf_path']}/config.xml") == 0) {
$last_backup = discover_last_backup();
if($last_backup) {
log_error("No config.xml found, attempting last known config restore.");
file_notice("config.xml", "No config.xml found, attempting last known config restore.", "pfSenseConfigurator", "");
restore_backup("{$g['conf_path']}/backup/{$last_backup}");
} else {
unlock($lockkey);
die("Config.xml is corrupted and is 0 bytes. Could not restore a previous backup.");
}
}
unlock($lockkey);
parse_config(true);
if ((float)$config['version'] > (float)$g['latest_config']) {
echo <<<EOD
*******************************************************************************
* WARNING! *
* The current configuration has been created with a newer version of {$g['product_name']} *
* than this one! This can lead to serious misbehavior and even security *
* holes! You are urged to either upgrade to a newer version of {$g['product_name']} or *
* revert to the default configuration immediately! *
*******************************************************************************
EOD;
}
/* make alias table (for faster lookups) */
alias_make_table($config);
}
/****f* config/conf_mount_rw
* NAME
* conf_mount_rw - Mount filesystems read/write.
* RESULT
* null
******/
/* mount flash card read/write */
function conf_mount_rw() {
global $g;
/* do not mount on cdrom platform */
if($g['platform'] == "cdrom" or $g['platform'] == "pfSense")
return;
if (is_subsystem_dirty('mount'))
return;
$status = mwexec("/sbin/mount -u -w {$g['cf_path']}");
if($status <> 0) {
if($g['booting'])
echo "Disk is dirty. Running fsck -y\n";
mwexec("/sbin/fsck -y {$g['cf_path']}");
$status = mwexec("/sbin/mount -u -w {$g['cf_path']}");
}
/* if the platform is soekris or wrap or pfSense, lets mount the
* compact flash cards root.
*/
if($g['platform'] == "wrap" or $g['platform'] == "net45xx"
or $g['platform'] == "embedded" or $g['platform'] == "nanobsd") {
$status = mwexec("/sbin/mount -u -w /");
/* we could not mount this correctly. kick off fsck */
if($status <> 0) {
log_error("File system is dirty. Launching FSCK for /");
mwexec("/sbin/fsck -y /");
$status = mwexec("/sbin/mount -u -w /");
}
}
mark_subsystem_dirty('mount');
}
/****f* config/conf_mount_ro
* NAME
* conf_mount_ro - Mount filesystems readonly.
* RESULT
* null
******/
function conf_mount_ro() {
global $g;
if($g['booting'] == true)
return;
/* firmare upgrade in progress */
if (is_subsystem_dirty('firmwarelock'))
return;
/* do not umount if generating ssh keys */
if (is_subsystem_dirty('sshdkeys'))
return;
/* do not umount on cdrom or pfSense platforms */
if($g['platform'] == "cdrom" or $g['platform'] == "pfSense")
return;
if (!is_subsystem_dirty('mount'))
return;
clear_subsystem_dirty('mount');
/* sync data, then force a remount of /cf */
mwexec("/bin/sync");
mwexec("/bin/sync");
mwexec("/sbin/mount -u -r -f {$g['cf_path']}");
mwexec("/sbin/mount -u -r -f /");
}
/****f* config/convert_config
* NAME
* convert_config - Attempt to update config.xml.
* DESCRIPTION
* convert_config() reads the current global configuration
* and attempts to convert it to conform to the latest
* config.xml version. This allows major formatting changes
* to be made with a minimum of breakage.
* RESULT
* null
******/
/* convert configuration, if necessary */
function convert_config() {
global $config, $g;
$now = date("H:i:s");
log_error("Start Configuration upgrade at $now, set execution timeout to 15 minutes");
ini_set("max_execution_time", "900");
/* special case upgrades */
/* fix every minute crontab bogons entry */
$cron_item_count = count($config['cron']['item']);
for($x=0; $x<$cron_item_count; $x++) {
if(stristr($config['cron']['item'][$x]['command'], "rc.update_bogons.sh")) {
if($config['cron']['item'][$x]['hour'] == "*" ) {
$config['cron']['item'][$x]['hour'] = "3";
write_config("Updated bogon update frequency to 3am");
log_error("Updated bogon update frequency to 3am");
}
}
}
if ($config['version'] == $g['latest_config'])
return; /* already at latest version */
// Save off config version
$prev_version = $config['version'];
include_once('upgrade_config.inc');
/* Loop and run upgrade_VER_to_VER() until we're at current version */
while ($config['version'] < $g['latest_config']) {
$cur = $config['version'] * 10;
$next = $cur + 1;
$migration_function = sprintf('upgrade_%03d_to_%03d', $cur, $next);
$migration_function();
$config['version'] = sprintf('%.1f', $next / 10);
echo ".";
}
$now = date("H:i:s");
log_error("Ended Configuration upgrade at $now");
if ($prev_version != $config['version'])
write_config("Upgraded config version level from {$prev_version} to {$config['version']}");
}
/****f* config/write_config
* NAME
* write_config - Backup and write the firewall configuration.
* DESCRIPTION
* write_config() handles backing up the current configuration,
* applying changes, and regenerating the configuration cache.
* INPUTS
* $desc - string containing the a description of configuration changes
* $backup - boolean: do not back up current configuration if false.
* RESULT
* null
******/
/* save the system configuration */
function write_config($desc="Unknown", $backup = true) {
global $config, $g;
if($g['bootup'])
log_error("WARNING! Configuration written on bootup. This can cause stray openvpn and load balancing items in config.xml");
if($backup)
backup_config();
if (time() > mktime(0, 0, 0, 9, 1, 2004)) /* make sure the clock settings are plausible */
$changetime = time();
/* Log the running script so it's not entirely unlogged what changed */
if ($desc == "Unknown")
$desc = "{$_SERVER['SCRIPT_NAME']} made unknown change";
$config['revision']['description'] = $desc;
$config['revision']['time'] = $changetime;
$lockkey = lock('config');
/* generate configuration XML */
$xmlconfig = dump_xml_config($config, $g['xml_rootobj']);
conf_mount_rw();
/* write new configuration */
$fd = fopen("{$g['cf_conf_path']}/config.xml", "w");
if (!$fd) {
// Unable to open temporary file for writing
log_error("WARNING: Config contents could not be save. Could not open file!");
unlock($lockkey);
return false;
}
if (!fwrite($fd, $xmlconfig)) {
// Unable to write to temporary file
log_error("WARNING: Config contents could not be written on file.");
fclose($fd);
unlock($lockkey);
return false;
}
fclose($fd);
if($g['platform'] == "embedded" or $g['platform'] == "nanobsd") {
cleanup_backupcache(5, true);
} else {
cleanup_backupcache(30, true);
}
/* re-read configuration */
$config = parse_xml_config("{$g['conf_path']}/config.xml", $g['xml_rootobj']);
/* write config cache */
$fd = @fopen("{$g['tmp_path']}/config.cache", "wb");
if ($fd) {
fwrite($fd, serialize($config));
fclose($fd);
}
/* tell kernel to sync fs data */
if (!$g['booting'])
conf_mount_ro();
unlock($lockkey);
unlink_if_exists("/usr/local/pkg/pf/carp_sync_client.php");
/* sync carp entries to other firewalls */
carp_sync_client();
if(is_dir("/usr/local/pkg/write_config")) {
/* process packager manager custom rules */
run_plugins("/usr/local/pkg/write_config/");
}
return $config;
}
/****f* config/reset_factory_defaults
* NAME
* reset_factory_defaults - Reset the system to its default configuration.
* RESULT
* integer - indicates completion
******/
function reset_factory_defaults($lock = false) {
global $g;
if (!$lock)
$lockkey = lock('config');
conf_mount_rw();
/* create conf directory, if necessary */
safe_mkdir("{$g['cf_conf_path']}");
/* clear out /conf */
$dh = opendir($g['conf_path']);
while ($filename = readdir($dh)) {
if (($filename != ".") && ($filename != "..")) {
unlink_if_exists($g['conf_path'] . "/" . $filename);
}
}
closedir($dh);
/* copy default configuration */
copy("{$g['conf_default_path']}/config.xml", "{$g['conf_path']}/config.xml");
/* call the wizard */
touch("/conf/trigger_initial_wizard");
conf_mount_ro();
if (!$lock)
unlock($lockkey);
return 0;
}
function config_restore($conffile) {
global $config, $g;
if (!file_exists($conffile))
return 1;
conf_mount_rw();
backup_config();
$lockkey = lock('config');
copy($conffile, "{$g['cf_conf_path']}/config.xml");
unlink_if_exists("{$g['tmp_path']}/config.cache");
unlock($lockkey);
$config = parse_config(true);
write_config("Reverted to " . array_pop(explode("/", $conffile)) . ".", false);
conf_mount_ro();
return 0;
}
function config_install($conffile) {
global $config, $g;
if (!file_exists($conffile))
return 1;
if (!config_validate("{$conffile}"))
return 1;
if($g['booting'] == true)
echo "Installing configuration...\n";
else
log_error("Installing configuration ....");
conf_mount_rw();
$lockkey = lock('config');
copy($conffile, "{$g['conf_path']}/config.xml");
/* unlink cache file if it exists */
if(file_exists("{$g['tmp_path']}/config.cache"))
unlink("{$g['tmp_path']}/config.cache");
unlock($lockkey);
conf_mount_ro();
return 0;
}
function config_validate($conffile) {
global $g, $xmlerr;
$xml_parser = xml_parser_create();
if (!($fp = fopen($conffile, "r"))) {
$xmlerr = "XML error: unable to open file";
return false;
}
while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
$xmlerr = sprintf("%s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser));
return false;
}
}
xml_parser_free($xml_parser);
fclose($fp);
return true;
}
function set_networking_interfaces_ports() {
global $noreboot;
global $config;
global $g;
global $fp;
$fp = fopen('php://stdin', 'r');
$memory = get_memory();
$avail = $memory[0];
if($avail < $g['minimum_ram_warning']) {
echo "\n\n\n";
echo "DANGER! WARNING! ACHTUNG!\n\n";
echo "{$g['product_name']} requires *AT LEAST* {$g['minimum_ram_warning_text']} RAM to function correctly.\n";
echo "Only ({$avail}) MB RAM has been detected.\n";
echo "\nPress ENTER to continue. ";
fgets($fp);
echo "\n";
}
$iflist = get_interface_list();
/* Function flow is based on $key and $auto_assign or the lack thereof */
$key = null;
/* Only present auto interface option if running from LiveCD and interface mismatch*/
if ((ereg("cdrom", $g['platform'])) && is_interface_mismatch())
$auto_assign = false;
echo <<<EOD
Valid interfaces are:
EOD;
if(!is_array($iflist)) {
echo "No interfaces found!\n";
$iflist = array();
} else {
foreach ($iflist as $iface => $ifa) {
echo sprintf("% -16s%s%s\t%s\n", $iface, $ifa['mac'],
$ifa['up'] ? " (up)" : " (down)", $ifa['dmesg']);
}
}
if ($auto_assign) {
echo <<<EOD
!!! LiveCD Detected: Auto Interface Option !!!!
BEGIN MANUAL CONFIGURATION OR WE WILL PROCEED WITH AUTO CONFIGURATION.
EOD;
}
echo <<<EOD
Do you want to set up VLANs first?
If you are not going to use VLANs, or only for optional interfaces, you should
say no here and use the webConfigurator to configure VLANs later, if required.
Do you want to set up VLANs now [y|n]?
EOD;
if ($auto_assign) {
$key = timeout();
} else
$key = chop(fgets($fp));
if (!isset($key) and $auto_assign) { // Auto Assign Interfaces
do {
echo <<<EOD
!!! Auto Assigning Interfaces !!!
For installation purposes, you must plug in at least one NIC
for the LAN connection. If you plug in a second NIC it will be
assigned to WAN. Otherwise, we'll temporarily assign WAN to the
next available NIC found regardless of activity. You should
assign and configure the WAN interface according to your requirements
If you haven't plugged in any network cables yet,
now is the time to do so.
We'll keep trying until you do.
Searching for active interfaces...
EOD;
unset($wanif, $lanif);
$media_iflist = $plugged_in = array();
$media_iflist = get_interface_list("media");
foreach ($media_iflist as $iface => $ifa) {
if ($ifa['up'])
$plugged_in[] = $iface;
}
$lanif = array_shift($plugged_in);
$wanif = array_shift($plugged_in);
if(isset($lanif) && !isset($wanif)) {
foreach ($iflist as $iface => $ifa) {
if ($iface != $lanif) {
$wanif = $iface;
break;
}
}
}
echo <<<EOD
Assigned WAN to : $wanif
Assigned LAN to : $lanif
If you don't like this assignment,
press any key to go back to manual configuration.
EOD;
$key = timeout(20);
if(isset($key))
return;
} while (!isset($wanif));
$config['system']['enablesshd'] = 'enabled';
$key = 'y';
} else { //Manually assign interfaces
if (in_array($key, array('y', 'Y')))
vlan_setup();
if (is_array($config['vlans']['vlan']) && count($config['vlans']['vlan'])) {
echo "\n\nVLAN interfaces:\n\n";
foreach ($config['vlans']['vlan'] as $vlan) {
echo sprintf("% -16s%s\n", "{$vlan['if']}_vlan{$vlan['tag']}",
"VLAN tag {$vlan['tag']}, parent interface {$vlan['if']}");
$iflist[$vlan['if'] . '_vlan' . $vlan['tag']] = array();
}
}
echo <<<EOD
*NOTE* {$g['product_name']} requires {$g['minimum_nic_count_text']} assigned interfaces to function.
If you do not have {$g['minimum_nic_count_text']} interfaces you CANNOT continue.
If you do not have at least {$g['minimum_nic_count']} *REAL* network interface cards
or one interface with multiple VLANs then {$g['product_name']}
*WILL NOT* function correctly.
If you do not know the names of your interfaces, you may choose to use
auto-detection. In that case, disconnect all interfaces now before
hitting 'a' to initiate auto detection.
EOD;
do {
echo "\nEnter the WAN interface name or 'a' for auto-detection: ";
$wanif = chop(fgets($fp));
if ($wanif === "") {
return;
}
if ($wanif === "a")
$wanif = autodetect_interface("WAN", $fp);
else if (!array_key_exists($wanif, $iflist)) {
echo "\nInvalid interface name '{$wanif}'\n";
unset($wanif);
continue;
}
} while (!$wanif);
do {
echo "\nEnter the LAN interface name or 'a' for auto-detection \n" .
"NOTE: this enables full Firewalling/NAT mode.\n" .
"(or nothing if finished): ";
$lanif = chop(fgets($fp));
if($lanif == "exit") {
exit;
}
if($lanif == "") {
if($g['minimum_nic_count'] < 2) {
break;
} else {
fclose($fp);
return;
}
}
if ($lanif === "a")
$lanif = autodetect_interface("LAN", $fp);
else if (!array_key_exists($lanif, $iflist)) {
echo "\nInvalid interface name '{$lanif}'\n";
unset($lanif);
continue;
}
} while (!$lanif);
/* optional interfaces */
$i = 0;
$optif = array();
if($lanif <> "") {
while (1) {
if ($optif[$i])
$i++;
$i1 = $i + 1;
if($config['interfaces']['opt' . $i1]['descr'])
echo "\nOptional interface {$i1} description found: {$config['interfaces']['opt' . $i1]['descr']}";
echo "\nEnter the Optional {$i1} interface name or 'a' for auto-detection\n" .
"(or nothing if finished): ";
$optif[$i] = chop(fgets($fp));
if ($optif[$i]) {
if ($optif[$i] === "a") {
$ad = autodetect_interface("Optional " . $i1, $fp);
if ($ad)
$optif[$i] = $ad;
else
unset($optif[$i]);
} else if (!array_key_exists($optif[$i], $iflist)) {
echo "\nInvalid interface name '{$optif[$i]}'\n";
unset($optif[$i]);
continue;
}
} else {
unset($optif[$i]);
break;
}
}
}
/* check for double assignments */
$ifarr = array_merge(array($lanif, $wanif), $optif);
for ($i = 0; $i < (count($ifarr)-1); $i++) {
for ($j = ($i+1); $j < count($ifarr); $j++) {
if ($ifarr[$i] == $ifarr[$j]) {
echo <<<EOD
Error: you cannot assign the same interface name twice!
EOD;
fclose($fp);
return;
}
}
}
echo "\nThe interfaces will be assigned as follows: \n\n";
if ($lanif != "")
echo "LAN ->" . $lanif . "\n";
echo "WAN ->" . $wanif . "\n";
for ($i = 0; $i < count($optif); $i++) {
echo "OPT" . ($i+1) . " -> " . $optif[$i] . "\n";
}
echo <<<EOD
Do you want to proceed [y|n]?
EOD;
$key = chop(fgets($fp));
}
if (in_array($key, array('y', 'Y'))) {
if($lanif) {
$config['interfaces']['lan']['if'] = $lanif;
} elseif (!$g['booting'] && !$auto_assign) {
echo <<<EODD
You have chosen to remove the LAN interface.
Would you like to remove the LAN IP address and
unload the interface now? [y|n]?
EODD;
if (strcasecmp(chop(fgets($fp)), "y") == 0) {
if($config['interfaces']['lan']['if'])
mwexec("/sbin/ifconfig delete " . $config['interfaces']['lan']['if']);
}
if(isset($config['interfaces']['lan']))
unset($config['interfaces']['lan']);
if(isset($config['dhcpd']['lan']))
unset($config['dhcpd']['lan']);
if(isset($config['interfaces']['lan']['if']))
unset($config['interfaces']['lan']['if']);
if(isset($config['interfaces']['wan']['blockpriv']))
unset($config['interfaces']['wan']['blockpriv']);
if(isset($config['shaper']))
unset($config['shaper']);
if(isset($config['ezshaper']))
unset($config['ezshaper']);
if(isset($config['nat']))
unset($config['nat']);
} else {
if(isset($config['interfaces']['lan']['if']))
mwexec("/sbin/ifconfig delete " . $config['interfaces']['lan']['if']);
if(isset($config['interfaces']['lan']))
unset($config['interfaces']['lan']);
if(isset($config['dhcpd']['lan']))
unset($config['dhcpd']['lan']);
if(isset($config['interfaces']['lan']['if']))
unset($config['interfaces']['lan']['if']);
if(isset($config['interfaces']['wan']['blockpriv']))
unset($config['interfaces']['wan']['blockpriv']);
if(isset($config['shaper']))
unset($config['shaper']);
if(isset($config['ezshaper']))
unset($config['ezshaper']);
if(isset($config['nat']))
unset($config['nat']);
}
if (preg_match($g['wireless_regex'], $lanif)) {
if (is_array($config['interfaces']['lan']) &&
(!is_array($config['interfaces']['lan']['wireless'])))
$config['interfaces']['lan']['wireless'] = array();
} else {
unset($config['interfaces']['lan']['wireless']);
}
$config['interfaces']['wan']['if'] = $wanif;
if (preg_match($g['wireless_regex'], $wanif)) {
if (is_array($config['interfaces']['lan']) &&
(!is_array($config['interfaces']['wan']['wireless'])))
$config['interfaces']['wan']['wireless'] = array();
} else {
unset($config['interfaces']['wan']['wireless']);
}
for ($i = 0; $i < count($optif); $i++) {
if (!is_array($config['interfaces']['opt' . ($i+1)]))
$config['interfaces']['opt' . ($i+1)] = array();
$config['interfaces']['opt' . ($i+1)]['if'] = $optif[$i];
/* wireless interface? */
if (preg_match($g['wireless_regex'], $optif[$i])) {
if (!is_array($config['interfaces']['opt' . ($i+1)]['wireless']))
$config['interfaces']['opt' . ($i+1)]['wireless'] = array();
} else {
unset($config['interfaces']['opt' . ($i+1)]['wireless']);
}
unset($config['interfaces']['opt' . ($i+1)]['enable']);
$config['interfaces']['opt' . ($i+1)]['descr'] = "OPT" . ($i+1);
}
/* remove all other (old) optional interfaces */
for (; isset($config['interfaces']['opt' . ($i+1)]); $i++)
unset($config['interfaces']['opt' . ($i+1)]);
echo "\nWriting configuration...";
write_config();
echo "done.\n";
echo <<<EOD
EOD;
fclose($fp);
if($g['booting'])
return;
echo "One moment while we reload the settings...";
$g['booting'] = false;
/* XXX: ermal - disable it for now this is used during bootup at best so shouldn't be needed.
* For now just comment it out and later remove it completely.
* resync everything
reload_all_sync();
*/
echo " done!\n";
touch("{$g['tmp_path']}/assign_complete");
}
}
function autodetect_interface($ifname, $fp) {
$iflist_prev = get_interface_list("media");
echo <<<EOD
Connect the {$ifname} interface now and make sure that the link is up.
Then press ENTER to continue.
EOD;
fgets($fp);
$iflist = get_interface_list("media");
foreach ($iflist_prev as $ifn => $ifa) {
if (!$ifa['up'] && $iflist[$ifn]['up']) {
echo "Detected link-up on interface {$ifn}.\n";
return $ifn;
}
}
echo "No link-up detected.\n";
return null;
}
function vlan_setup() {
global $iflist, $config, $g, $fp;
$iflist = get_interface_list();
if (is_array($config['vlans']['vlan']) && count($config['vlans']['vlan'])) {
echo <<<EOD
WARNING: all existing VLANs will be cleared if you proceed!
Do you want to proceed [y|n]?
EOD;
if (strcasecmp(chop(fgets($fp)), "y") != 0)
return;
}
$config['vlans']['vlan'] = array();
echo "\n";
$vlanif = 0;
while (1) {
$vlan = array();
echo "\n\nVLAN Capable interfaces:\n\n";
if(!is_array($iflist)) {
echo "No interfaces found!\n";
} else {
$vlan_capable=0;
foreach ($iflist as $iface => $ifa) {
if (is_jumbo_capable($iface)) {
echo sprintf("% -8s%s%s\n", $iface, $ifa['mac'],
$ifa['up'] ? " (up)" : "");
$vlan_capable++;
}
}
}
if($vlan_capable == 0) {
echo "No VLAN capable interfaces detected.\n";
return;
}
echo "\nEnter the parent interface name for the new VLAN (or nothing if finished): ";
$vlan['if'] = chop(fgets($fp));
if ($vlan['if']) {
if (!array_key_exists($vlan['if'], $iflist) or
!is_jumbo_capable($vlan['if'])) {
echo "\nInvalid interface name '{$vlan['if']}'\n";
continue;
}
} else {
break;
}
echo "Enter the VLAN tag (1-4094): ";
$vlan['tag'] = chop(fgets($fp));
$vlan['vlanif'] = "{$vlan['if']}_vlan{$vlan['tag']}";
if (!is_numericint($vlan['tag']) || ($vlan['tag'] < 1) || ($vlan['tag'] > 4094)) {
echo "\nInvalid VLAN tag '{$vlan['tag']}'\n";
continue;
}
$config['vlans']['vlan'][] = $vlan;
$vlanif++;
}
}
function cleanup_backupcache($revisions = 30, $lock = false) {
global $g;
$i = false;
if (!$lock)
$lockkey = lock('config');
if(file_exists($g['cf_conf_path'] . '/backup/backup.cache')) {
conf_mount_rw();
$backups = get_backups();
$newbaks = array();
$bakfiles = glob($g['cf_conf_path'] . "/backup/config-*");
$baktimes = $backups['versions'];
$tocache = array();
unset($backups['versions']);
foreach($bakfiles as $backup) { // Check for backups in the directory not represented in the cache.
if(filesize($backup) == 0) {
unlink($backup);
continue;
}
$tocheck = array_shift(explode('.', array_pop(explode('-', $backup))));
if(!in_array($tocheck, $baktimes)) {
$i = true;
if($g['booting'])
echo ".";
$newxml = parse_xml_config($backup, $g['xml_rootobj']);
if($newxml == "-1") {
log_error("The backup cache file $backup is corrupted. Unlinking.");
unlink($backup);
log_error("The backup cache file $backup is corrupted. Unlinking.");
continue;
}
if($newxml['revision']['description'] == "")
$newxml['revision']['description'] = "Unknown";
$tocache[$tocheck] = array('description' => $newxml['revision']['description']);
}
}
foreach($backups as $checkbak) {
if(count(preg_grep('/' . $checkbak['time'] . '/i', $bakfiles)) != 0) {
$newbaks[] = $checkbak;
} else {
$i = true;
if($g['booting']) print " " . $tocheck . "r";
}
}
foreach($newbaks as $todo) $tocache[$todo['time']] = array('description' => $todo['description']);
if(is_int($revisions) and (count($tocache) > $revisions)) {
$toslice = array_slice(array_keys($tocache), 0, $revisions);
foreach($toslice as $sliced)
$newcache[$sliced] = $tocache[$sliced];
foreach($tocache as $version => $versioninfo) {
if(!in_array($version, array_keys($newcache))) {
unlink_if_exists($g['conf_path'] . '/backup/config-' . $version . '.xml');
if($g['booting']) print " " . $tocheck . "d";
}
}
$tocache = $newcache;
}
$bakout = fopen($g['cf_conf_path'] . '/backup/backup.cache', "w");
fwrite($bakout, serialize($tocache));
fclose($bakout);
conf_mount_ro();
}
if($g['booting'] && $i)
print "done.\n";
if (!$lock)
unlock($lockkey);
}
function get_backups() {
global $g;
if(file_exists("{$g['cf_conf_path']}/backup/backup.cache")) {
$confvers = unserialize(file_get_contents("{$g['cf_conf_path']}/backup/backup.cache"));
$bakvers = array_keys($confvers);
$toreturn = array();
sort($bakvers);
// $bakvers = array_reverse($bakvers);
foreach(array_reverse($bakvers) as $bakver)
$toreturn[] = array('time' => $bakver, 'description' => $confvers[$bakver]['description']);
} else {
return false;
}
$toreturn['versions'] = $bakvers;
return $toreturn;
}
function backup_config() {
global $config, $g;
if($g['platform'] == "cdrom")
return;
conf_mount_rw();
/* Create backup directory if needed */
safe_mkdir("{$g['cf_conf_path']}/backup");
if($config['revision']['time'] == "") {
$baktime = 0;
} else {
$baktime = $config['revision']['time'];
}
if($config['revision']['description'] == "") {
$bakdesc = "Unknown";
} else {
$bakdesc = $config['revision']['description'];
}
copy($g['cf_conf_path'] . '/config.xml', $g['cf_conf_path'] . '/backup/config-' . $baktime . '.xml');
if(file_exists($g['cf_conf_path'] . '/backup/backup.cache')) {
$backupcache = unserialize(file_get_contents($g['cf_conf_path'] . '/backup/backup.cache'));
} else {
$backupcache = array();
}
$backupcache[$baktime] = array('description' => $bakdesc);
$bakout = fopen($g['cf_conf_path'] . '/backup/backup.cache', "w");
fwrite($bakout, serialize($backupcache));
fclose($bakout);
conf_mount_ro();
return true;
}
function set_device_perms() {
$devices = array(
'pf' => array( 'user' => 'proxy',
'group' => 'proxy',
'mode' => 0660),
);
foreach ($devices as $name => $attr) {
$path = "/dev/$name";
if (file_exists($path)) {
chown($path, $attr['user']);
chgrp($path, $attr['group']);
chmod($path, $attr['mode']);
}
}
}
if($g['booting']) echo ".";
$config = parse_config();
if($config_parsed == true) {
/* process packager manager custom rules */
if(is_dir("/usr/local/pkg/parse_config")) {
run_plugins("/usr/local/pkg/parse_config/");
}
}
?>
|