-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcompile-csf.php
More file actions
1115 lines (954 loc) · 52.9 KB
/
Copy pathcompile-csf.php
File metadata and controls
1115 lines (954 loc) · 52.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Configuration compiler for ConfigServer Firewall & LFD
* -----------------------------------------------------------------------------
* By Adam "Adambean" Reece - www.reece.wales
* https://github.com/Adambean/compile-csf
*
* This nifty little tool will help you deploy a centralised configuration for
* CSF+LFD to multiple managed servers. Certain files, such as "csf.conf", are
* even compiled for each server according to the operating system it runs.
*
* Please check the corresponding "README.md" for instructions on using this.
*
* Reminder for new operating system releases: To build a pre-defined set of
* binary pathnames, use the command in "detect-bins.sh" from a shell on that
* system.
* -----------------------------------------------------------------------------
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* "LICENSE" for the specific language governing permissions and limitations
* under the License.
*/
printf("Configuration compiler for ConfigServer Firewall & LFD\n\n");
if (PHP_VERSION_ID < 70200) {
printf("[Critical] PHP 7.2 or later required.\n");
exit(1);
}
// << Check required functions are available
$requiredFunctionsMissing = 0;
foreach ([
"ssh2_auth_agent",
"ssh2_auth_pubkey_file",
"ssh2_connect",
"ssh2_exec",
"ssh2_fingerprint",
] as $requiredFunction) {
if (!function_exists($requiredFunction)) {
printf("[Critical] Required function \"%s\" is not available. Please check your PHP has the necessary extensions available.\n", $requiredFunction);
++$requiredFunctionsMissing;
}
}
if ($requiredFunctionsMissing) {
exit(1);
}
// >> Check required functions are available
/** @var bool $sshUsePageant Attempt to use an SSH key agent for authentication. (Pageant.) */
$sshUsePageant = true;
/** @var string|null $sshKeyFilePublic SSH public key file to use for authentication. (OpenSSH format.) */
$sshKeyFilePublic = null;
/** @var string|null $sshKeyFilePrivate SSH private key file to use for authentication. (OpenSSH format.) */
$sshKeyFilePrivate = null;
/** @var string|null $sshKeyFilePassword SSH private key password if encrypted. (This will show in PS!) */
$sshKeyFilePassword = null;
/** @var string[] $serversToAction Limit action to these servers. */
$serversToAction = [];
/** @var int $serversToActionNum Count of `$serversToAction`. */
$serversToActionNum = 0;
/** @var string $serversFileType Server list file type. */
$serversFileType = "yml";
/** @var string[] $serversFileTypes Server list file types that are supported. (This should be a constant really.) */
$serversFileTypes = ["json", "yml", "yaml"];
/** @var bool $enableDownload Try to download for merges? (Lists for allow/deny.) */
$enableDownload = true;
/** @var bool $enableUpload Try to upload after compilation? */
$enableUpload = true;
/** @var bool $enableRestart Restart CSF and LFD after upload? */
$enableRestart = true;
define("CSF_PER_SERVER_LINE", "### SERVER SPECIFIC ENTRIES BELOW THIS LINE ### DO NOT EDIT/REMOVE THIS LINE ###");
/**
* Show usage of this command and exit.
* @param int|null $exitCode Exit code, or null to not exit
* @return null
*/
function showUsage(?int $exitCode = 0): null
{
if (null !== $exitCode && $exitCode) {
printf("\n");
}
printf("Usage:\n\n");
printf("\t--help Show usage.\n");
printf("\n");
printf("\t--nopageant Do not attempt to use an SSH key agent for authentication. (Pageant.)\n");
printf("\t--sshkeypublic=file SSH public key file to use for authentication. (OpenSSH format.)\n");
printf("\t--sshkeyprivate=file SSH private key file to use for authentication. (OpenSSH format.)\n");
printf("\t--sshkeypassword=passowrd SSH private key password if encrypted. (This will show in PS!)\n");
printf("\t--sshkeypasswordfile=file SSH private key password if encrypted from a file. (This will show in PS!)\n");
printf("\n");
printf("\t--servers=name1,name2,... Only action specific servers. (Split multiple with a comma.)\n");
printf("\t--serversfiletype=type Server list file type. (Type can be json, yml, or yaml.)\n");
printf("\n");
printf("\t--download Enable download for merges. (Lists for allow and deny.)\n");
printf("\t--nodownload Disable download for merges. (Lists for allow and deny.)\n");
printf("\t--upload Enable upload after compilation.\n");
printf("\t--noupload Disable upload after compilation.\n");
printf("\t--restart Enable service restart after upload.\n");
printf("\t--norestart Disable service restart after upload.\n");
if (null !== $exitCode) {
exit($exitCode);
}
return $exitCode;
}
foreach ($argv as $i => $arg) {
if (0 === $i) {
continue; // Ignore script name
}
/** @var string[] $argMatches */
$argMatches = [];
if (preg_match("/--([a-zA-Z0-9-]+)=?(.*)?/", $arg, $argMatches) !== false && count($argMatches) >= 2) {
$argSwitch = strtolower(trim($argMatches[1]));
$argValue = isset($argMatches[2]) ? trim($argMatches[2]) : null;
switch ($argSwitch) {
case "help":
return showUsage();
case "sshkeypublic":
case "sshkeyprivate":
$argKeyType = substr($argSwitch, 6);
if (!is_string($argValue) || "" === ($argValue = trim($argValue))) {
printf("[Error] %s SSH key file not specified.\n", $argKeyType);
return showUsage(1);
}
if (!file_exists($argValue) || !is_file($argValue) /*|| !is_readable($argValue)*/) {
printf("[Error] %s SSH key file not found, not a file, or not readable.\n", $argKeyType);
return showUsage(1);
}
$sshKeyFileVar = sprintf("sshKeyFile%s", ucfirst($argKeyType));
$$sshKeyFileVar = $argValue;
printf("SSH %s key file defined as \"%s\".\n", $argKeyType, $argValue);
break;
case "sshkeypassword":
if (!is_string($argValue) || "" === ($argValue = trim($argValue))) {
printf("[Error] SSH key password not specified.\n");
return showUsage(1);
}
$sshKeyFilePassword = $argValue;
printf("SSH private key password set.\n");
break;
case "sshkeypasswordfile":
if (!is_string($argValue) || "" === ($argValue = trim($argValue))) {
printf("[Error] SSH key password file not specified.\n");
return showUsage(1);
}
if (!file_exists($argValue) || !is_file($argValue) /*|| !is_readable($argValue)*/) {
printf("[Error] SSH key password file not found, not a file, or not readable.\n");
return showUsage(1);
}
if ("" === ($sshKeyFilePassword = strval(file_get_contents($argValue)))) {
printf("[Error] SSH key password not specified in file.\n");
return showUsage(1);
}
printf("SSH private key password set from file.\n");
break;
case "nopageant":
$sshUsePageant = false;
printf("SSH key agent will not be used.\n");
break;
case "servers":
if (!is_string($argValue) || "" === ($argValue = trim($argValue))) {
printf("[Error] Servers not specified.\n");
return showUsage(1);
}
$argServers = explode(',', $argValue);
if ([] === $argServers) {
printf("[Error] Servers not specified.\n");
return showUsage(1);
}
foreach ($argServers as &$serverToAction) {
if ($serverToAction = trim($serverToAction)) {
$serversToAction[] = $serverToAction;
}
}
$serversToActionNum = count($serversToAction);
printf("Only the following %d server(s) will be actioned: %s\n", $serversToActionNum, implode(", ", $serversToAction));
break;
case "download":
$enableDownload = true;
printf("Download enabled.\n");
break;
case "nodownload":
$enableDownload = false;
printf("Download disabled.\n");
break;
case "upload":
$enableUpload = true;
printf("Upload enabled.\n");
break;
case "noupload":
$enableUpload = false;
printf("Upload disabled.\n");
break;
case "restart":
$enableRestart = true;
printf("Restart enabled.\n");
break;
case "norestart":
$enableRestart = false;
printf("Restart disabled.\n");
break;
case "serverfiletype":
if (!is_string($argValue) || "" === ($argValue = trim($argValue))) {
printf("[Error] Servers file type not specified.\n");
return showUsage(1);
}
if (!in_array($argValue, $serversFileTypes)) {
printf("[Error] Servers file type \"%s\" invalid.\n", $argValue);
return showUsage(1);
}
$serversFileType = $argValue;
printf("Server list file type set to \"%s\".\n", $serversFileType);
break;
default:
printf("Switch \"%s\" invalid.\n\n", $argSwitch);
return showUsage(1);
}
} else {
printf("Argument #%d \"%s\" invalid.\n\n", $i, $arg);
return showUsage(1);
}
}
if (
!boolval($sshUsePageant)
&& (
null === $sshKeyFilePublic
|| (!($sshKeyFilePublic = trim($sshKeyFilePublic)))
|| null === $sshKeyFilePrivate
|| (!($sshKeyFilePrivate = trim($sshKeyFilePrivate)))
)
) {
printf("[Error] Viable SSH authentication method not available.\nPlease use a key agent (Pageant) or key files (OpenSSH format).\n");
return showUsage(1);
}
printf("\nLoading base configuration...\n");
$directoryCsfBase = sprintf("%s/_all/etc/csf", __DIR__);
if (!is_dir($directoryCsfBase)) {
printf("- Base CSF directory not found, creating...\n");
mkdir($directoryCsfBase, 0770, true);
if (!is_dir($directoryCsfBase)) {
printf("[Error] Failed to create base CSF directory \"%s\".\n", $directoryCsfBase);
exit(1);
}
}
printf("\nLoading servers...\n");
$serversFileType = trim($serversFileType);
if (!in_array($serversFileType, $serversFileTypes)) {
printf("[Error] Servers file type \"%s\" invalid.\n", $serversFileType);
exit(1);
}
/** @var string $serversFile Servers list file. */
$serversFile = sprintf("%s.%s", substr(__FILE__, 0, intval(strrpos(__FILE__, '.'))), $serversFileType);
/** @var string $serversFileSample Servers list sample file. */
$serversFileSample = sprintf("%s.sample.%s", substr(__FILE__, 0, intval(strrpos(__FILE__, '.'))), $serversFileType);
if (!file_exists($serversFile) || !is_file($serversFile) /*|| !is_readable($serversFile)*/) {
printf("[Error] Server list file \"%s\" not found, not a file, or not readable.\n", $serversFile);
if (file_exists($serversFileSample) && is_file($serversFileSample)) {
printf("I see that the sample server list file \"%s\" exists though.\nYou should make a copy of this as \"%s\" then configure it.\n", $serversFileSample, $serversFile);
}
exit(1);
}
/** @var array<string, array<string, mixed>> $servers Servers list. */
$servers = [];
switch ($serversFileType) {
case "json":
try {
/** @var array<string, array<string, mixed>> $servers Servers list. */
$servers = json_decode(strval(file_get_contents($serversFile)), true, 512, JSON_THROW_ON_ERROR|JSON_INVALID_UTF8_SUBSTITUTE);
} catch (JsonException $e) {
printf("[Critical] Servers file could not be decoded: %s\n", $e->getMessage());
exit(1);
} catch (\Exception $e) {
printf("[Critical] Servers file could not be read: %s\n", $e->getMessage());
exit(1);
}
break;
case "yml":
case "yaml":
if (!function_exists("yaml_parse_file")) {
printf("[Critical] YAML for PHP is not installed. If this is a problem you must use JSON instead.\n");
exit(1);
}
/** @var array<string, array<string, mixed>> $servers Servers list. */
$servers = yaml_parse_file($serversFile);
break;
default:
printf("[Error] Servers file type \"%s\" invalid.\n", $serversFileType);
exit(1);
}
if (($serverCount = count($servers)) < 1) {
printf("[Error] Servers configuration is empty.\n");
exit(1);
}
printf("Found %d server(s) in configuration, %d to process.\n", $serverCount, ($serversToActionNum >= 1 ? $serversToActionNum : $serverCount));
printf("\nLooking at server list...\n");
/** @var string[] $allServersAsCluster All server addresses in the cluster. */
$allServersAsCluster = [];
foreach ($servers as $s => $server) {
if ('_' === substr($s, 0, 1)) {
printf("[Warning] Ignoring server \"%s\" because it starts with a special character.\n", $s);
unset($servers[$s]);
continue;
}
if (isset($server["noClusterRules"]) && $server["noClusterRules"]) {
continue;
}
foreach (["ipv4", "ipv6"] as $k) {
if (isset($server[$k]) && is_string($server[$k]) && "" !== ($clusterMemberAddress = trim($server[$k]))) {
$allServersAsCluster[] = $clusterMemberAddress;
break; // We're doing this because we don't want to add BOTH IPv4 and IPv6. Just add the first one that got defined.
}
}
}
/** @var string $allServersAsClusterString All server addresses in the cluster imploded. */
$allServersAsClusterString = implode(",", $allServersAsCluster);
printf("\nProcessing servers...\n");
/** @var resource|null $linkSsh SSH session handle. */
$linkSsh = null;
/** @var bool $linkSshAuthed SSH session has authenticated. */
$linkSshAuthed = false;
/** @var resource|null $linkSftp SFTP session handle. */
$linkSftp = null;
foreach ($servers as $s => $server) {
$s = trim(strval($s));
if ("" === $s || $s == "_all" || !is_array($server) || [] === $server) {
continue;
}
// Is this server skipped?
if ($serversToActionNum >= 1 && !in_array($s, $serversToAction, true)) {
continue;
}
// Show server name
printf("%s:\n", $s);
$serverAddress = $s;
try {
// << SSH connection: Open
printf("- Establishing SSH and SFTP link...\n");
if (isset($linkSsh) && $linkSsh && is_resource($linkSsh)) {
if (false === ssh2_exec($linkSsh, "exit")) {
printf("- SSH connection to previous server did not close cleanly.\n");
}
$linkSsh = null;
$linkSshAuthed = false;
$linkSftp = null;
}
if (!isset($server["hostname"]) || !is_string($server["hostname"])) {
throw new \UnexpectedValueException("Host name not defined or not a string.");
}
if ("" === ($server["hostname"] = trim($server["hostname"]))) {
throw new \UnexpectedValueException("Host name not specified.");
}
if (!isset($server["portSsh"]) || !is_int($server["portSsh"])) {
throw new \UnexpectedValueException("SSH port not defined or not an integer.");
}
if ($server["portSsh"] < 1 || $server["portSsh"] > 65535) {
throw new \UnexpectedValueException(sprintf("SSH port %d invalid.", $server["portSsh"]));
}
if (!isset($server["sshFingerprint"])) {
throw new \UnexpectedValueException("SSH fingerprint not defined.");
}
if (
(is_array($server["sshFingerprint"]) && [] === $server["sshFingerprint"])
|| (is_string($server["sshFingerprint"]) && "" === ($server["sshFingerprint"] = trim($server["sshFingerprint"])))
) {
throw new UnexpectedValueException("SSH fingerprint not specified.");
}
foreach (["hostname", "ipv6", "ipv4"] as $k) {
if (
isset($server[$k])
&& is_scalar($server[$k])
&& "" !== ($serverAddress = trim(strval($server[$k])))
&& is_resource($linkSsh = ssh2_connect($serverAddress, $server["portSsh"]))
) {
break; // Connection established
}
}
if (!$linkSsh || !is_resource($linkSsh)) {
throw new \RuntimeException("SSH connection failed.");
}
printf("- - SSH connection established to \"%s\".\n", $serverAddress);
$sshFingerprint = trim(strval(ssh2_fingerprint($linkSsh, SSH2_FINGERPRINT_SHA1|SSH2_FINGERPRINT_HEX)));
if ("" === $sshFingerprint) {
throw new \RuntimeException("SSH server did not return a fingerprint.");
}
if (
(is_array($server["sshFingerprint"]) && !in_array($sshFingerprint, $server["sshFingerprint"]))
|| (is_string($server["sshFingerprint"]) && $sshFingerprint != $server["sshFingerprint"])
) {
throw new \RuntimeException(sprintf(
"SSH fingerprint mismatch. (Presented with %s, but should be %s.)",
$sshFingerprint,
is_array($server["sshFingerprint"])
? implode("/", $server["sshFingerprint"])
: $server["sshFingerprint"]
));
}
printf("- - SSH fingerprint verified. (%s)\n", $sshFingerprint);
if (!$linkSshAuthed && $sshUsePageant) {
if (ssh2_auth_agent($linkSsh, "root")) {
printf("- - SSH connection authenticated. (Key agent.)\n");
$linkSshAuthed = true;
} else {
printf("- - SSH connection failed. (Key agent.)\n");
}
}
if (!$linkSshAuthed && $sshKeyFilePublic && $sshKeyFilePrivate) {
if (ssh2_auth_pubkey_file($linkSsh, "root", $sshKeyFilePublic, $sshKeyFilePrivate, is_string($sshKeyFilePassword) ? $sshKeyFilePassword : "")) {
printf("- - SSH connection authenticated. (Key pair.)\n");
$linkSshAuthed = true;
} else {
printf("- - SSH connection failed. (Key pair.)\n");
}
}
if (!$linkSshAuthed) {
throw new \RuntimeException("SSH connection authentication failed. (No method available.)");
}
if (!($linkSftp = ssh2_sftp($linkSsh))) {
throw new \RuntimeException("SFTP connection failed.");
}
printf("- - SFTP connection established.\n");
// >> SSH connection: Open
// << Directory: Server
$directory = sprintf("%s/%s", __DIR__, $s);
if (!is_dir($directory)) {
printf("- Directory not found, creating...\n");
mkdir($directory, 0770, true);
if (!is_dir($directory)) {
throw new \RuntimeException(sprintf("Failed to create directory: \"%s\".", $directory));
}
}
// >> Directory: Server
if (!isset($server["pathCsf"]) || !is_scalar($server["pathCsf"]) || "" === ($directoryCsf = trim(strval($server["pathCsf"])))) {
$directoryCsf = "/etc/csf";
}
// << Directory: CSF (remote)
$directoryCsfR = sprintf("ssh2.sftp://%s%s", strval($linkSftp), $directoryCsf);
if (!is_dir($directoryCsfR)) {
printf("- CSF directory (remote) not found. Is CSF installed on this server?\n");
continue;
}
// >> Directory: CSF (remote)
// << Directory: CSF (local)
$directoryCsfL = sprintf("%s/%s", $directory, $directoryCsf);
if (!is_dir($directoryCsfL)) {
printf("- CSF directory (local) not found, creating...\n");
mkdir($directoryCsfL, 0750, true);
if (!is_dir($directoryCsfL)) {
throw new \RuntimeException(sprintf("Failed to create CSF directory (local): \"%s\".", $directoryCsfL));
}
}
// >> Directory: CSF (local)
// << Build: CSF/LFD
printf("- Building configuration...\n");
if (is_iterable($directoryCsfBaseContents = scandir($directoryCsfBase))) {
foreach (scandir($directoryCsfBase) as $c) {
$c = trim($c);
$cPath = sprintf("%s/%s", $directoryCsfBase, $c);
$lPath = sprintf("%s/%s", $directoryCsfL, $c);
$rPath = sprintf("%s/%s", $directoryCsf, $c);
$rPathF = sprintf("%s/%s", $directoryCsfR, $c);
if (!is_file($cPath)) {
continue;
}
switch ($c) {
case "csf.allow":
case "csf.deny":
// << Merge server-specific lines into a template
if ($enableDownload) {
printf("- - Checking for file \"%s\" on remote server...\n", $c);
if (file_exists($rPathF)) {
if (!ssh2_scp_recv($linkSsh, $rPath, $lPath)) {
printf("- - - Found on remote server, but couldn't download it!\n");
}
printf("- - - Downloaded from remote server.\n");
}
}
if (!file_exists($lPath) || !is_file($lPath) || filesize($lPath) < 1) {
printf("- - Copying: %s\n", $c);
copy($cPath, $lPath);
break;
}
printf("- - Merging: %s\n", $c);
$cContent = strval(file_get_contents($cPath));
$lContent = strval(file_get_contents($lPath));
$mContent = $cContent;
$lSplit = null;
if (false === strpos($lContent, CSF_PER_SERVER_LINE)) {
$lSplit = 0;
printf("- - - Not found server specific split.\n");
}
$lContents = preg_split("/[\r\n]/", $lContent);
if (is_iterable($lContents)) {
foreach ($lContents as $l => $line) {
if ($line == CSF_PER_SERVER_LINE) {
$lSplit = $l;
printf("- - - Found server specific split. (%d)\n", $l);
if (strpos($mContent, CSF_PER_SERVER_LINE) !== false) {
continue;
}
}
if ($lSplit !== null && (substr($line, 0, 1) !== '#' || intval($lSplit) >= 1)) {
if ($line) {
$mContent .= sprintf("%s\n", $line);
}
}
}
}
$mContent = trim($mContent) . "\n";
if (false === file_put_contents($lPath, $mContent)) {
printf("- - - Failed to write merged content. Copying base instead...\n");
copy($cPath, $lPath);
}
break;
// >> Merge server-specific lines into a template
case "csf.conf":
// << Build specifically for this server using a template
printf("- - Building: %s\n", $c);
if (!isset($server["csfConf"]) || !is_array($server["csfConf"]) || count($server["csfConf"]) < 1) {
printf("- - - No CSF configuration defined for server. Copying base instead...\n");
copy($cPath, $lPath);
$server["csfConf"] = [];
}
// Cluster members: Rule sharing at runtime
if ((!isset($server["noClusterRules"]) || !$server["noClusterRules"]) && $allServersAsClusterString) {
$server["csfConf"]["CLUSTER_SENDTO"] = $allServersAsClusterString;
$server["csfConf"]["CLUSTER_RECVFROM"] = $allServersAsClusterString;
}
// Container specific
switch ($server["container"]) {
case "virtuozzo":
case "openvz":
$server["csfConf"]["LF_IPSET"] = 0;
break;
default:
$server["csfConf"]["LF_IPSET"] = 1;
}
// Type specific
switch ($server["type"]) {
case "whm":
$server["csfConf"]["GENERIC"] = 0;
$server["csfConf"]["PT_APACHESTATUS"] = "http://127.0.0.1/whm-server-status";
break;
default:
$server["csfConf"]["GENERIC"] = 1;
$server["csfConf"]["PT_APACHESTATUS"] = "http://127.0.0.1/server-status";
}
// OS specific
switch ($server["os"]) {
case "centos6":
case "rhel6":
case "cloudlinux6":
$server["csfConf"] = array_merge([
"CSF" => "/usr/sbin/csf",
"IPTABLES" => "/sbin/iptables",
"IPTABLES_SAVE" => "/sbin/iptables-save",
"IPTABLES_RESTORE" => "/sbin/iptables-restore",
"IP6TABLES" => "/sbin/ip6tables",
"IP6TABLES_SAVE" => "/sbin/ip6tables-save",
"IP6TABLES_RESTORE" => "/sbin/ip6tables-restore",
"MODPROBE" => "/sbin/modprobe",
"IFCONFIG" => "/sbin/ifconfig",
"SENDMAIL" => "/usr/sbin/sendmail",
"PS" => "/bin/ps",
"VMSTAT" => "/usr/bin/vmstat",
"NETSTAT" => "/bin/netstat",
"LS" => "/bin/ls",
"MD5SUM" => "/usr/bin/md5sum",
"TAR" => "/bin/tar",
"CHATTR" => "/usr/bin/chattr",
"UNZIP" => "/usr/bin/unzip",
"GUNZIP" => "/bin/gunzip",
"DD" => "/bin/dd",
"TAIL" => "/usr/bin/tail",
"GREP" => "/bin/grep",
"IPSET" => "/usr/sbin/ipset",
"SYSTEMCTL" => "/usr/bin/systemctl",
"HOST" => "/usr/bin/host",
"IP" => "/sbin/ip",
"HTACCESS_LOG" => "/usr/local/apache/logs/error_log",
"MODSEC_LOG" => "/usr/local/apache/logs/error_log",
"SSHD_LOG" => "/var/log/secure",
"SU_LOG" => "/var/log/secure",
"FTPD_LOG" => "/var/log/messages",
"SMTPAUTH_LOG" => "/var/log/exim_mainlog",
"SMTPRELAY_LOG" => "/var/log/exim_mainlog",
"POP3D_LOG" => "/var/log/maillog",
"IMAPD_LOG" => "/var/log/maillog",
"CPANEL_LOG" => "/usr/local/cpanel/logs/login_log",
"CPANEL_ACCESSLOG" => "/usr/local/cpanel/logs/access_log",
"SCRIPT_LOG" => "/var/log/exim_mainlog",
"IPTABLES_LOG" => "/var/log/messages",
"SUHOSIN_LOG" => "/var/log/messages",
"BIND_LOG" => "/var/log/messages",
"SYSLOG_LOG" => "/var/log/messages",
"WEBMIN_LOG" => "/var/log/secure",
], $server["csfConf"]);
break;
case "rhel7":
case "centos7":
case "cloudlinux7":
$server["csfConf"] = array_merge([
"CSF" => "/usr/sbin/csf",
"IPTABLES" => "/sbin/iptables",
"IPTABLES_SAVE" => "/sbin/iptables-save",
"IPTABLES_RESTORE" => "/sbin/iptables-restore",
"IP6TABLES" => "/sbin/ip6tables",
"IP6TABLES_SAVE" => "/sbin/ip6tables-save",
"IP6TABLES_RESTORE" => "/sbin/ip6tables-restore",
"MODPROBE" => "/sbin/modprobe",
"IFCONFIG" => "/sbin/ifconfig",
"SENDMAIL" => "/usr/sbin/sendmail",
"PS" => "/usr/bin/ps",
"VMSTAT" => "/usr/bin/vmstat",
"NETSTAT" => "/usr/bin/netstat",
"LS" => "/usr/bin/ls",
"MD5SUM" => "/usr/bin/md5sum",
"TAR" => "/usr/bin/tar",
"CHATTR" => "/usr/bin/chattr",
"UNZIP" => "/usr/bin/unzip",
"GUNZIP" => "/usr/bin/gunzip",
"DD" => "/usr/bin/dd",
"TAIL" => "/usr/bin/tail",
"GREP" => "/bin/grep",
"IPSET" => "/usr/sbin/ipset",
"SYSTEMCTL" => "/usr/bin/systemctl",
"HOST" => "/usr/bin/host",
"IP" => "/usr/sbin/ip",
"HTACCESS_LOG" => "/usr/local/apache/logs/error_log",
"MODSEC_LOG" => "/usr/local/apache/logs/error_log",
"SSHD_LOG" => "/var/log/secure",
"SU_LOG" => "/var/log/secure",
"FTPD_LOG" => "/var/log/messages",
"SMTPAUTH_LOG" => "/var/log/exim_mainlog",
"SMTPRELAY_LOG" => "/var/log/exim_mainlog",
"POP3D_LOG" => "/var/log/maillog",
"IMAPD_LOG" => "/var/log/maillog",
"CPANEL_LOG" => "/usr/local/cpanel/logs/login_log",
"CPANEL_ACCESSLOG" => "/usr/local/cpanel/logs/access_log",
"SCRIPT_LOG" => "/var/log/exim_mainlog",
"IPTABLES_LOG" => "/var/log/messages",
"SUHOSIN_LOG" => "/var/log/messages",
"BIND_LOG" => "/var/log/messages",
"SYSLOG_LOG" => "/var/log/messages",
"WEBMIN_LOG" => "/var/log/secure",
], $server["csfConf"]);
break;
case "rhel8":
case "centos8":
case "almalinux8":
case "cloudlinux8":
case "rhel9":
case "centos9":
case "almalinux9":
case "cloudlinux9":
$server["csfConf"] = array_merge([
"CSF" => "/usr/sbin/csf",
"IPTABLES" => "/usr/sbin/iptables",
"IPTABLES_SAVE" => "/usr/sbin/iptables-save",
"IPTABLES_RESTORE" => "/usr/sbin/iptables-restore",
"IP6TABLES" => "/usr/sbin/ip6tables",
"IP6TABLES_SAVE" => "/usr/sbin/ip6tables-save",
"IP6TABLES_RESTORE" => "/usr/sbin/ip6tables-restore",
"MODPROBE" => "/usr/sbin/modprobe",
"IFCONFIG" => "/usr/sbin/ifconfig",
"SENDMAIL" => "/usr/sbin/sendmail",
"PS" => "/usr/bin/ps",
"VMSTAT" => "/usr/bin/vmstat",
"NETSTAT" => "/usr/bin/netstat",
"LS" => "/usr/bin/ls",
"MD5SUM" => "/usr/bin/md5sum",
"TAR" => "/usr/bin/tar",
"CHATTR" => "/usr/bin/chattr",
"UNZIP" => "/usr/bin/unzip",
"GUNZIP" => "/usr/bin/gunzip",
"DD" => "/usr/bin/dd",
"TAIL" => "/usr/bin/tail",
"GREP" => "/usr/bin/grep",
"IPSET" => "/usr/sbin/ipset",
"SYSTEMCTL" => "/usr/bin/systemctl",
"HOST" => "/usr/bin/host",
"IP" => "/usr/sbin/ip",
"HTACCESS_LOG" => "/usr/local/apache/logs/error_log",
"MODSEC_LOG" => "/usr/local/apache/logs/error_log",
"SSHD_LOG" => "/var/log/secure",
"SU_LOG" => "/var/log/secure",
"FTPD_LOG" => "/var/log/messages",
"SMTPAUTH_LOG" => "/var/log/exim_mainlog",
"SMTPRELAY_LOG" => "/var/log/exim_mainlog",
"POP3D_LOG" => "/var/log/maillog",
"IMAPD_LOG" => "/var/log/maillog",
"CPANEL_LOG" => "/usr/local/cpanel/logs/login_log",
"CPANEL_ACCESSLOG" => "/usr/local/cpanel/logs/access_log",
"SCRIPT_LOG" => "/var/log/exim_mainlog",
"IPTABLES_LOG" => "/var/log/messages",
"SUHOSIN_LOG" => "/var/log/messages",
"BIND_LOG" => "/var/log/messages",
"SYSLOG_LOG" => "/var/log/messages",
"WEBMIN_LOG" => "/var/log/secure",
], $server["csfConf"]);
break;
case "debian8":
case "ubuntu-16.04":
$server["csfConf"] = array_merge([
"CSF" => "/usr/sbin/csf",
"IPTABLES" => "/sbin/iptables",
"IPTABLES_SAVE" => "/sbin/iptables-save",
"IPTABLES_RESTORE" => "/sbin/iptables-restore",
"IP6TABLES" => "/sbin/ip6tables",
"IP6TABLES_SAVE" => "/sbin/ip6tables-save",
"IP6TABLES_RESTORE" => "/sbin/ip6tables-restore",
"MODPROBE" => "/sbin/modprobe",
"IFCONFIG" => "/sbin/ifconfig",
"SENDMAIL" => "/usr/sbin/sendmail",
"PS" => "/bin/ps",
"VMSTAT" => "/usr/bin/vmstat",
"NETSTAT" => "/bin/netstat",
"LS" => "/bin/ls",
"MD5SUM" => "/usr/bin/md5sum",
"TAR" => "/bin/tar",
"CHATTR" => "/usr/bin/chattr",
"UNZIP" => "/usr/bin/unzip",
"GUNZIP" => "/bin/gunzip",
"DD" => "/bin/dd",
"TAIL" => "/usr/bin/tail",
"GREP" => "/bin/grep",
"IPSET" => "/sbin/ipset",
"SYSTEMCTL" => "/bin/systemctl",
"HOST" => "/usr/bin/host",
"IP" => "/sbin/ip",
"HTACCESS_LOG" => "/var/log/apache2/error.log",
"MODSEC_LOG" => "/var/log/apache2/error.log",
"SSHD_LOG" => "/var/log/auth.log",
"SU_LOG" => "/var/log/messages",
"FTPD_LOG" => "/var/log/messages",
"SMTPAUTH_LOG" => "/var/log/exim4/mainlog",
"SMTPRELAY_LOG" => "/var/log/exim4/mainlog",
"POP3D_LOG" => "/var/log/exim4/mainlog",
"IMAPD_LOG" => "/var/log/exim4/mainlog",
"IPTABLES_LOG" => "/var/log/messages",
"SUHOSIN_LOG" => "/var/log/messages",
"BIND_LOG" => "/var/log/messages",
"SYSLOG_LOG" => "/var/log/syslog",
"WEBMIN_LOG" => "/var/log/auth.log",
], $server["csfConf"]);
break;
case "debian9":
case "debian10":
case "debian11":
case "debian12":
case "debian13":
case "ubuntu-20.04":
case "ubuntu-22.04":
case "ubuntu-24.04":
$server["csfConf"] = array_merge([
"CSF" => "/usr/sbin/csf",
"IPTABLES" => "/usr/sbin/iptables",
"IPTABLES_SAVE" => "/usr/sbin/iptables-save",
"IPTABLES_RESTORE" => "/usr/sbin/iptables-restore",
"IP6TABLES" => "/usr/sbin/ip6tables",
"IP6TABLES_SAVE" => "/usr/sbin/ip6tables-save",
"IP6TABLES_RESTORE" => "/usr/sbin/ip6tables-restore",
"MODPROBE" => "/usr/sbin/modprobe",
"IFCONFIG" => "/usr/sbin/ifconfig",
"SENDMAIL" => "/usr/sbin/sendmail",
"PS" => "/usr/bin/ps",
"VMSTAT" => "/usr/bin/vmstat",
"NETSTAT" => "/usr/bin/netstat",
"LS" => "/usr/bin/ls",
"MD5SUM" => "/usr/bin/md5sum",
"TAR" => "/usr/bin/tar",
"CHATTR" => "/usr/bin/chattr",
"UNZIP" => "/usr/bin/unzip",
"GUNZIP" => "/usr/bin/gunzip",
"DD" => "/usr/bin/dd",
"TAIL" => "/usr/bin/tail",
"GREP" => "/usr/bin/grep",
"IPSET" => "/usr/sbin/ipset",
"SYSTEMCTL" => "/usr/bin/systemctl",
"HOST" => "/usr/bin/host",
"IP" => "/usr/sbin/ip",
"HTACCESS_LOG" => "/var/log/apache2/error.log",
"MODSEC_LOG" => "/var/log/apache2/error.log",
"SSHD_LOG" => "/var/log/auth.log",
"SU_LOG" => "/var/log/messages",
"FTPD_LOG" => "/var/log/messages",
"SMTPAUTH_LOG" => "/var/log/exim4/mainlog",
"SMTPRELAY_LOG" => "/var/log/exim4/mainlog",
"POP3D_LOG" => "/var/log/exim4/mainlog",
"IMAPD_LOG" => "/var/log/exim4/mainlog",
"IPTABLES_LOG" => "/var/log/messages",
"SUHOSIN_LOG" => "/var/log/messages",
"BIND_LOG" => "/var/log/messages",
"SYSLOG_LOG" => "/var/log/syslog",
"WEBMIN_LOG" => "/var/log/auth.log",
], $server["csfConf"]);
break;
}
// Detect locations of binaries automatically
if (!isset($server["explicitBins"]) || !is_scalar($server["explicitBins"]) || !boolval($server["explicitBins"])) {
foreach ([
"CSF" => "csf",
"IPTABLES" => "iptables",
"IPTABLES_SAVE" => "iptables-save",
"IPTABLES_RESTORE" => "iptables-restore",
"IP6TABLES" => "ip6tables",
"IP6TABLES_SAVE" => "ip6tables-save",
"IP6TABLES_RESTORE" => "ip6tables-restore",
"MODPROBE" => "modprobe",
"IFCONFIG" => "ifconfig",
"SENDMAIL" => "sendmail",
"PS" => "ps",
"VMSTAT" => "vmstat",
"NETSTAT" => "netstat",
"LS" => "ls",
"MD5SUM" => "md5sum",
"TAR" => "tar",
"CHATTR" => "chattr",
"UNZIP" => "unzip",
"GUNZIP" => "gunzip",
"DD" => "dd",
"TAIL" => "tail",
"GREP" => "grep",
"IPSET" => "ipset",
"SYSTEMCTL" => "systemctl",
"HOST" => "host",
"IP" => "ip",
] as $bin => $binFile) {
if (false === ($binLocator = ssh2_exec($linkSsh, sprintf("type -P %s", $binFile)))) {
printf("- - - Binary \"%s\" search failed. Using default location instead...\n", $bin);
continue;
}
stream_set_blocking($binLocator, true);
$binLocatorOut = ssh2_fetch_stream($binLocator, SSH2_STREAM_STDIO);
if (!is_resource($binLocatorOut)) {
printf("- - - Binary \"%s\" search failed.\n", $bin);
continue;
}
if ("" === ($binLocation = trim(strval(stream_get_contents($binLocatorOut))))) {
printf("- - - Binary \"%s\" not found. It might not be installed...\n", $bin);
continue;
}
$server["csfConf"][$bin] = $binLocation;
printf("- - - Binary \"%s\" found at \"%s\".\n", $bin, $binLocation);
}
}
$cContent = file_get_contents($cPath);
$bContent = "";
if (is_string($cContent) && "" !== $cContent) {
$sContents = preg_split("/[\r\n]/", $cContent);
if (is_iterable($sContents)) {
foreach ($sContents as $l => $line) {
$lineToWrite = trim($line);
foreach ($server["csfConf"] as $confKey => $confValue) {