forked from Bloke/smd_prognostics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmd_prognostics.php
More file actions
1910 lines (1599 loc) · 88.9 KB
/
Copy pathsmd_prognostics.php
File metadata and controls
1910 lines (1599 loc) · 88.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
// This is a PLUGIN TEMPLATE for Textpattern CMS.
// Copy this file to a new name like abc_myplugin.php. Edit the code, then
// run this file at the command line to produce a plugin for distribution:
// $ php abc_myplugin.php > abc_myplugin-0.1.txt
// Plugin name is optional. If unset, it will be extracted from the current
// file name. Plugin names should start with a three letter prefix which is
// unique and reserved for each plugin author ("abc" is just an example).
// Uncomment and edit this line to override:
$plugin['name'] = 'smd_prognostics';
// Allow raw HTML help, as opposed to Textile.
// 0 = Plugin help is in Textile format, no raw HTML allowed (default).
// 1 = Plugin help is in raw HTML. Not recommended.
# $plugin['allow_html_help'] = 1;
$plugin['version'] = '0.5.1';
$plugin['author'] = 'Stef Dawson';
$plugin['author_uri'] = 'https://stefdawson.com/';
$plugin['description'] = 'Pro-active diagnostics that alarm when things have changed in Textpattern';
// Plugin load order:
// The default value of 5 would fit most plugins, while for instance comment
// spam evaluators or URL redirectors would probably want to run earlier
// (1...4) to prepare the environment for everything else that follows.
// Values 6...9 should be considered for plugins which would work late.
// This order is user-overrideable.
$plugin['order'] = '1';
// Plugin 'type' defines where the plugin is loaded
// 0 = public : only on the public side of the website (default)
// 1 = public+admin : on both the public and admin side
// 2 = library : only when include_plugin() or require_plugin() is called
// 3 = admin : only on the admin side (no AJAX)
// 4 = admin+ajax : only on the admin side (AJAX supported)
// 5 = public+admin+ajax : on both the public and admin side (AJAX supported)
$plugin['type'] = '1';
// Plugin "flags" signal the presence of optional capabilities to the core plugin loader.
// Use an appropriately OR-ed combination of these flags.
// The four high-order bits 0xf000 are available for this plugin's private use
if (!defined('PLUGIN_HAS_PREFS')) define('PLUGIN_HAS_PREFS', 0x0001); // This plugin wants to receive "plugin_prefs.{$plugin['name']}" events
if (!defined('PLUGIN_LIFECYCLE_NOTIFY')) define('PLUGIN_LIFECYCLE_NOTIFY', 0x0002); // This plugin wants to receive "plugin_lifecycle.{$plugin['name']}" events
$plugin['flags'] = '1';
// Plugin 'textpack' is optional. It provides i18n strings to be used in conjunction with gTxt().
// Syntax:
// ## arbitrary comment
// #@event
// #@language ISO-LANGUAGE-CODE
// abc_string_name => Localized String
$plugin['textpack'] = <<<EOT
#@language en, en-gb, en-us
#@admin-side
smd_prognostics => Prognostics
#@smd_prognostics
smd_prognostics_acked => Alarms acknowledged.
smd_prognostics_alarm_freq => Alarm on detection and every:
smd_prognostics_and => and
smd_prognostics_auth_users => Restrict prognostic config to:
smd_prognostics_block => Block
smd_prognostics_btn_ackit => Acknowledge
smd_prognostics_btn_csi => Send Forensics
smd_prognostics_btn_ignore => Ignore
smd_prognostics_check_between => Check files between:
smd_prognostics_check_for => Check files for:
smd_prognostics_check_freq => Check files (at most) every:
smd_prognostics_check_qty => Check this many files each time:
smd_prognostics_check_where => Check files on public side clicks:
smd_prognostics_ch_add => Additions
smd_prognostics_ch_del => Deletions
smd_prognostics_ch_mod => Modifications
smd_prognostics_csense => (case-sensitive)
smd_prognostics_csi_sent => Forensics data sent
smd_prognostics_csv => (comma-separated)
smd_prognostics_currmon => You are currently monitoring {curr} out of {outof} available files.
smd_prognostics_docroot_files => Consider moving the "files" folder outside of your site root folder. You can do this via the "Admin > Preferences > Admin > File directory path" setting.
smd_prognostics_docroot_prognostics => Please change the "Prognostics folder" setting to a directory outside your site root folder.
smd_prognostics_docroot_tmp => Consider moving the "tmp" folder outside of your site root folder. You can do this via the "Admin > Preferences > Admin > Temporary directory path" setting.
smd_prognostics_excludir => Exclude folders:
smd_prognostics_files_updated => File list updated
smd_prognostics_help_link => (<a href="{link}">Help</a>)
smd_prognostics_hms => (hrs:mins:secs)
smd_prognostics_ignores => Ignore files:
smd_prognostics_lbl_added => Added (not monitored)
smd_prognostics_lbl_changed => Changed
smd_prognostics_lbl_hashmod => COMPROMISED
smd_prognostics_lbl_missing => Missing
smd_prognostics_listloc => File locations:
smd_prognostics_mailto => Send e-mail to:
smd_prognostics_mailto_csi => Send forensics to:
smd_prognostics_monfiles_explain => Select all the files you wish to monitor and click Save. Altering this list will automatically acknowledge any outstanding alarms against the selected files.
smd_prognostics_none_selected => No files selected
smd_prognostics_notify_email => E-mail
smd_prognostics_notify_txp => Txp interface
smd_prognostics_notify_via => Notify via:
smd_prognostics_not_writable => {location} is not a directory or is not writable
smd_prognostics_no_alarms => No alarms to acknowledge at present.
smd_prognostics_no_files => No files to list. Check the plugin setup (and Save it).
smd_prognostics_no_log_entries => No log activity around the time of the differences.
smd_prognostics_pnl_ack => Alarms
smd_prognostics_pnl_advice => Advice
smd_prognostics_pnl_files => Files
smd_prognostics_pnl_setup => Setup
smd_prognostics_postamble => Acknowledge alarms
smd_prognostics_preamble_added => These files have been added:
smd_prognostics_preamble_files => File contents follows:
smd_prognostics_preamble_hashdown => WARNING! The checksums file is missing.
smd_prognostics_preamble_hashmod => WARNING! The checksums file has been altered:
smd_prognostics_preamble_miss => These files are missing:
smd_prognostics_preamble_nok => These files differ from their expected content:
smd_prognostics_preamble_sql_inject => Possible SQL injection detected
smd_prognostics_preamble_txplog => Log entries prior to this detection:
smd_prognostics_progloc => Prognostics folder:
smd_prognostics_progpfx => Unique prefix:
smd_prognostics_req_headers => Block request headers:
smd_prognostics_req_not_allowed => REQUEST_METHOD not allowed: {req}
smd_prognostics_rh_del => DELETE
smd_prognostics_rh_put => PUT
smd_prognostics_rh_trace => TRACE
smd_prognostics_rpc_exists => The rpc directory is not being used. Consider removing it.
smd_prognostics_rt_hdr => Header violations
smd_prognostics_rt_sql => SQL injections
smd_prognostics_seconds => (seconds)
smd_prognostics_send_forensics => Send forensics for:
smd_prognostics_sensitivity => Sensitivity threshold:
smd_prognostics_sensitivity_explain => (1=most sensitive)
smd_prognostics_setup_exists => The setup directory still exists. Please delete it.
smd_prognostics_show_grants => Your Txp user can access the MySQL privileges in the DB. Consider accessing the DB using a less privileged user.
smd_prognostics_sql_file_privs => Your MySQL user has FILE privileges. Consider revoking this right unless absolutely necessary.
smd_prognostics_sql_inject => Protect against SQL injection:
smd_prognostics_stat_gid => Group ID:
smd_prognostics_stat_mod => Modified:
smd_prognostics_stat_name => Filename:
smd_prognostics_stat_size => Size:
smd_prognostics_stat_uid => User ID:
smd_prognostics_subject => Prognostics ({site})
smd_prognostics_subject_csi => Prognostics ({site}) forensics
smd_prognostics_tight => You run a pretty tight ship. Stay frosty.
smd_prognostics_ttl_ack => Prognostic alarm acknowledgement
smd_prognostics_ttl_advice => Prognostic advice
smd_prognostics_ttl_fileopts => Filesystem options
smd_prognostics_ttl_files => Prognostic file monitoring
smd_prognostics_ttl_monopts => Monitoring options
smd_prognostics_ttl_plugopts => Plugin options
smd_prognostics_ttl_realopts => Realtime options
smd_prognostics_ttl_setup => Prognostic setup
smd_prognostics_txpdir => Admin-side URL:
smd_prognostics_warn_loc => File locations changed. Update your <a href="index.php?event=smd_prognostics&;step=smd_prognostics_files">list of files</a> now
smd_prognostics_with => with:
smd_prognostics_xss => XSS shield:
smd_prognostics_xss_explain => (may break Textiled comments)
EOT;
if (!defined('txpinterface'))
@include_once('zem_tpl.php');
# --- BEGIN PLUGIN CODE ---
/**
* smd_prognostics
*
* A Textpattern CMS plugin for pro-active diagnostics
* -> Detect changes to the file system
* -> Acknowledge alarms (sent via e-mail or to the admin interface)
*
* @author Stef Dawson
* @link https://stefdawson.com/
* @todo Monitor PHP / MySQL version? (https://forum.textpattern.io/viewtopic.php?pid=260163#p260163)
*/
global $smd_prognostics_event, $smd_prognostics_checksums, $smd_prognostics_sqlprot;
$smd_prognostics_event = 'smd_prognostics';
$smd_prognostics_checksums = rtrim(get_pref('smd_prognostics_dir', txpath, 1), DS) . DS . get_pref('smd_prognostics_prefix', '').'smd_prognostics_checksums.txt';
$hdron = get_pref('smd_prognostics_req_headers', '');
$smd_prognostics_sqlprot = new smd_prog_PhProtector(false);
if (txpinterface === 'admin') {
global $txp_user, $event, $step;
$smd_prognostics_privs = '1,2';
$smd_prognostics_suppress = gps('smd_prognostics_suppress');
$privs = safe_field("privs", "txp_users", "name = '".doSlash($txp_user)."'");
$users = get_pref('smd_prognostics_users', '');
$allow = ($users) ? in_array($txp_user, do_list($users)) : true;
if ($allow) {
add_privs($smd_prognostics_event, $smd_prognostics_privs);
add_privs('plugin_prefs.'.$smd_prognostics_event, $smd_prognostics_privs);
register_tab('extensions', $smd_prognostics_event, gTxt('smd_prognostics'));
register_callback('smd_prognostics_setup', 'plugin_prefs.'.$smd_prognostics_event);
register_callback('smd_prognostics_dispatcher', $smd_prognostics_event);
register_callback('smd_prognostics_inject_css', 'admin_side', 'head_end');
}
if ($hdron) {
register_callback('smd_prognostics_request_headers', 'admin_side', 'head_end');
}
// Admin side callback for checking files
if (!$smd_prognostics_suppress && in_array($privs, do_list($smd_prognostics_privs))) {
register_callback('smd_prognostics', 'admin_side', 'main_content');
}
}
// Public side callbacks
if (strpos(get_pref('smd_prognostics_check_where', ''), 'public') !== false) {
register_callback('smd_prognostics', 'pretext');
}
if ($hdron) {
register_callback('smd_prognostics_request_headers', 'pretext');
}
if (strpos(get_pref('smd_prognostics_sql_inject', 'smd_no'), 'smd_no') === false) {
register_callback('smd_prognostics_sql_inject', 'pretext');
}
// -------------------------------------------------------------
// CSS definitions: hopefully kind to themers.
function smd_prognostics_get_style_rules()
{
$smd_prognostics_styles = array(
'msg' =>
'.smd_prog_warn { margin:0 auto 10px; width:500px; background:#ffc; border:2px dashed red; padding:10px; color:#444; }
.smd_prog_warn a { font-weight:bold; color:#963; }
.smd_prog_warn span { font-weight:bold; }
.smd_prog_warn div { font-weight:bold; padding-bottom:10px; }',
'setup' =>
'.smd_label { text-align:right!important; vertical-align:middle; }
.smd_prog_btns form { display:inline; }
.smd_prognostics_setup h3 { margin:25px 0 0; }',
'advice' =>
'.smd_prog_advice { width:750px; }
#list.smd_prog_advice td { padding:5px; }
.smd_prog_btns { width:140px; }',
);
return $smd_prognostics_styles;
}
// -------------------------------------------------------------
function smd_prognostics_inject_css($evt, $stp)
{
global $smd_prognostics_event, $event, $step;
if ($event == $smd_prognostics_event) {
$smd_prognostics_style = smd_prognostics_get_style_rules();
$styles = array();
switch ($step) {
case 'smd_prognostics_advice':
$styles[] = 'advice';
$styles[] = 'setup';
break;
}
if ($styles) {
echo '<style type="text/css">';
foreach ($styles as $style) {
echo $smd_prognostics_style[$style];
}
echo '</style>';
}
}
return;
}
// ------------------------
function smd_prognostics_dispatcher($evt, $stp)
{
$available_steps = array(
'smd_prognostics_files' => false,
'smd_prognostics_setup' => false,
'smd_prognostics_advice' => false,
'smd_prognostics_ack' => false,
);
if (!$stp or !bouncer($stp, $available_steps)) {
$stp = 'smd_prognostics_setup';
}
$stp();
}
// Stub to call the verification code from the URL
function smd_prognostics($evt, $stp)
{
return smd_do_prognostics();
}
// Verify the file checksums
// $mode = 0: normal / 1: no update (return arrays only) / 2: silent update
function smd_do_prognostics($mode = 0)
{
global $smd_prognostics_event, $smd_prognostics_checksums;
$smd_prognostics_style = smd_prognostics_get_style_rules();
$now = time();
$nok = $miss = $added = $allfiles = $hashdown = $hashmod = array();
$timenow = date('H:i:s', $now);
list($beg, $end) = do_list(get_pref('smd_prognostics_check_between', '|'), '|'); // Default is pipe so we can guarantee two return vals
$tdiff = ($mode == 1 || ( ($timenow > $beg) && ($timenow < $end) && ($now - get_pref('smd_prognostics_lastcheck', 0) > get_pref('smd_prognostics_check_freq', 3600)) ) ) ? true : false;
// Parts shamelessly plagiarised from txp_diag
if ($tdiff) {
$sumhash = get_pref('smd_prognostics_sumhash', NULL, ($mode==1 ? 1 : 0));
$lookat = get_pref('smd_prognostics_check_for', '');
$adds = (strpos($lookat, 'add') !== false);
$dels = (strpos($lookat, 'delete') !== false);
$mods = (strpos($lookat, 'modify') !== false);
if ($cs = @file($smd_prognostics_checksums)) {
$hash = md5(smd_prognostics_prep_file($smd_prognostics_checksums));
if ($hash != $sumhash) {
$hashmod[] = $smd_prognostics_checksums;
} else {
$ctr = 0;
$qty_per = (($qty = get_pref('smd_prognostics_check_qty', '')) == '') ? count($cs) : $qty;
$so_far = get_pref('smd_prognostics_qty_so_far', 0);
$until = $so_far + $qty_per;
foreach ($cs as $c) {
if (preg_match('@^(\S+): \((.*)\)$@', trim($c), $m)) {
list(,$file,$md5) = $m;
if ($dels && !file_exists($file)) {
$miss[] = $file;
} elseif ($mods && $md5 != 'NULL') {
// Check file_exists last as it's the slowest operation; allows PHP to short circuit conditionals faster
if ( ( (($ctr >= $so_far) && ($ctr < $until) || $mode == 1) ) && file_exists($file) ) {
$content = smd_prognostics_prep_file($file);
if ((md5($content) != $md5) && ($file != $smd_prognostics_checksums)) {
$nok[] = $file;
}
}
$ctr++;
}
$allfiles[] = $file;
}
}
// Stash the story so far ready for next time the function is called
if ($mode != 1) {
set_pref('smd_prognostics_qty_so_far', (($until < $ctr) ? $until : 0), 'smd_prognos', PREF_HIDDEN, 'text_input');
}
if ($adds) {
$filelist = smd_prognostics_readfiles();
$added = array_diff($filelist, $allfiles);
}
if ($mode != 1) {
set_pref('smd_prognostics_lastcheck', $now, 'smd_prognos', PREF_HIDDEN, 'text_input');
}
}
} else {
// File doesn't exist
$hashdown[] = $smd_prognostics_checksums;
}
}
// Assemble message
if ($nok || $miss || $added || $hashdown || $hashmod) {
if ($mode == 1) {
return array($nok, $miss, $added, $hashdown, $hashmod);
} else {
$via = get_pref('smd_prognostics_notify_via', '');
$detect = get_pref('smd_prognostics_lastdetect', '');
$lasts = explode(',', get_pref('smd_prognostics_lastact', 0));
$freqs = explode(',', get_pref('smd_prognostics_alarm_freq', 86400));
if (!isset($lasts[1])) {
$lasts[1] = $lasts[0];
}
if (!isset($freqs[1])) {
$freqs[1] = $freqs[0];
}
$lastact_txp = ($mode < 2 && ($now - $lasts[0] > $freqs[0])) ? true : false;
$lastact_mail = ($mode < 2 && ($now - $lasts[1] > $freqs[1])) ? true : false;
$lastmsg = get_pref('smd_prognostics_lastmsg', '');
$subject = gTxt('smd_prognostics_subject', array('{site}' => get_pref('siteurl')));
$msg = join('|', array_merge($hashdown, $hashmod, $nok, $miss, $added));
if (txpinterface === 'admin' && strpos($via, 'txp') !== false) {
if ($lastact_txp || ($lastmsg != md5($msg))) {
$txpdir = get_pref('smd_prognostics_txpdir', hu.smd_prognostics_guess_admin_dir());
$out = '<style type="text/css">'.$smd_prognostics_style['msg'].'</style><div class="smd_prog_warn"><div>'.$subject.'</div>'.
(($hashdown) ? '<p>'.gTxt('smd_prognostics_preamble_hashdown').'</p><ul><li>'.join('</li><li>',$hashdown).'</li></ul>' : '').
(($hashmod) ? '<p>'.gTxt('smd_prognostics_preamble_hashmod').'</p><ul><li>'.join('</li><li>',$hashmod).'</li></ul>' : '').
(($nok) ? '<p>'.gTxt('smd_prognostics_preamble_nok').'</p><ul><li>'.join('</li><li>',$nok).'</li></ul>' : '').
(($miss) ? '<p>'.gTxt('smd_prognostics_preamble_miss').'</p><ul><li>'.join('</li><li>',$miss).'</li></ul>' : '').
(($added) ? '<p>'.gTxt('smd_prognostics_preamble_added').'</p><ul><li>'.join('</li><li>',$added).'</li></ul>' : '').
'<p><a href="'.$txpdir.'/index.php?event='.$smd_prognostics_event.a.'step=smd_prognostics_ack'.a.'smd_prognostics_suppress=1">'.
gTxt('smd_prognostics_postamble').'</a></p></div>';
set_pref('smd_prognostics_lastact', $now.','.$lasts[1], 'smd_prognos', PREF_HIDDEN, 'text_input');
echo $out;
}
}
if (strpos($via, 'email') !== false) {
if ($lastact_mail || ($lastmsg != md5($msg))) {
$to = get_pref('smd_prognostics_mailto', '');
if ($to) {
$hdrs = smd_prognostics_header_info('smd_prognostics');
$body =
(($hashdown) ? n.gTxt('smd_prognostics_preamble_hashdown').n.n.join(n,$hashdown) : '').
(($hashmod) ? n.gTxt('smd_prognostics_preamble_hashmod').n.n.join(n,$hashmod) : '').
(($nok) ? n.gTxt('smd_prognostics_preamble_nok').n.n.join(n,$nok) : '').
(($miss) ? n.n.gTxt('smd_prognostics_preamble_miss').n.n.join(n,$miss) : '').
(($added) ? n.n.gTxt('smd_prognostics_preamble_added').n.n.join(n,$added) : '').
n.n.'<a href="'.$hdrs['txpdir'].'/index.php?event='.$smd_prognostics_event.a.'step=smd_prognostics_ack'.a.'smd_prognostics_suppress=1">'.gTxt('smd_prognostics_postamble').'</a>';
mail($to, $subject, $body, $hdrs['headers']);
}
set_pref('smd_prognostics_lastact', $lasts[0].','.$now, 'smd_prognos', PREF_HIDDEN, 'text_input');
}
}
set_pref('smd_prognostics_lastmsg', md5($msg), 'smd_prognos', PREF_HIDDEN, 'text_input');
if ($lastmsg != md5($msg)) {
if ($detect == '') {
set_pref('smd_prognostics_lastdetect', $now, 'smd_prognos', PREF_HIDDEN, 'text_input');
} else {
$detect = explode(',',$detect);
set_pref('smd_prognostics_lastdetect', $detect[0].','.$now, 'smd_prognos', PREF_HIDDEN, 'text_input');
}
}
}
}
}
// ----------
// Catch unexpected request headers
function smd_prognostics_request_headers($evt, $stp)
{
$block = explode('|', get_pref('smd_prognostics_req_headers', ''));
$hdr = serverSet('REQUEST_METHOD');
if (in_array($hdr, $block)) {
$send = (strpos(get_pref('smd_prognostics_rt_forensics'), 'hdr') !== false);
// Send the forensics off if necessary
$to = get_pref('smd_prognostics_mailto_csi', '');
if ($to && $send) {
$subject = gTxt('smd_prognostics_subject_csi', array('{site}' => get_pref('siteurl')));
$hdrs = smd_prognostics_header_info('smd_frognostics');
$body = n.gTxt('smd_prognostics_req_not_allowed', array('{req}' => $hdr)).n;
foreach ($_SERVER + $_REQUEST + $_ENV as $key => $var) {
$body .= n.$key.': '.$var;
}
mail($to, $subject, $body, $hdrs['headers']);
}
//TODO: offer alternative die mechanisms like SQL attacks?
exit(1);
}
}
// ----------
// SQL injection detection
function smd_prognostics_sql_inject()
{
global $smd_prognostics_sqlprot, $permlink_mode, $DB;
// Determine comment preview step and ignore if so
$is_prevu = false;
$com = psa(array(
'parentid',
'preview',
'backpage',
));
if ($com['preview']) {
$urlparts = explode('/', $com['backpage']);
$num = ($permlink_mode == 'messy') ? 1 : count($urlparts);
$artic = safe_field('id','textpattern', "ID=".doSlash($com['parentid']).(($num > 1) ? " AND url_title='".doSlash($urlparts[$num-1])."'" : ''));
$is_prevu = ($artic) ? true : false;
}
if (!$is_prevu && $smd_prognostics_sqlprot->isMalicious()) {
$opts = do_list(get_pref('smd_prognostics_sql_inject', '|'), '|');
$blok = (strpos($opts[0], 'smd_block') !== false);
$send = (strpos(get_pref('smd_prognostics_rt_forensics'), 'sql') !== false);
$ver = (defined('txp_version')) ? txp_version : get_pref('version', '');
// Send the forensics off if necessary
$to = get_pref('smd_prognostics_mailto_csi', '');
if ($to && $send) {
$subject = gTxt('smd_prognostics_subject_csi', array('{site}' => get_pref('siteurl')));
$hdrs = smd_prognostics_header_info('smd_frognostics');
$body = n.gTxt('smd_prognostics_preamble_sql_inject').n;
$body .= (($ver) ? 'Txp: ' . $ver .n : '') . 'PHP: ' . phpversion() .n. 'MySQL: ' . mysqli_get_server_info($DB->link) .n. ((is_callable('apache_get_version')) ? 'Apache: ' . apache_get_version().n : '');
foreach ($_SERVER + $_REQUEST + $_ENV as $key => $var) {
$body .= n.$key.': '.$var;
}
mail($to, $subject, $body, $hdrs['headers']);
}
if (isset($opts[1]) && !empty($opts[1])) {
$parts = do_list($opts[1], ':');
if ($parts[0] == 'txp_form') {
$msg = parse_form($parts[1]);
} else {
$msg = $opts[1];
}
} else {
$msg = '';
}
if ($blok) {
echo $msg;
exit(1);
} else {
txp_die($msg, $opts[0]);
}
}
}
// -----------------
// Admin-side panels
// -----------------
// ----------
// Alarm acknowledgement
function smd_prognostics_ack($msg = '')
{
global $smd_prognostics_event, $smd_prognostics_checksums, $prefs, $DB;
$method = ps('edit_method');
$submit = ($method == 'acknowledge');
$ignore = ($method == 'ignore');
$csi = ($method == 'csi');
$ack = gps('selected');
$smd_prog_ack = (is_array($ack)) ? $ack : (($ack) ? array($ack) : array());
$out = array();
if ($submit || $ignore) {
if ($cs = @file($smd_prognostics_checksums)) {
foreach ($cs as $c) {
if (preg_match('@^(\S+): \((.*)\)$@', trim($c), $m)) {
list(,$file,$md5) = $m;
if (($key = array_search($file, $smd_prog_ack)) !== false) {
if (file_exists($file)) {
$content = smd_prognostics_prep_file($file);
$out[] = $file.': ('.( ($ignore) ? 'NULL' : md5($content) ).')';
}
// Remove files that already have checksums so we're left with additions
unset($smd_prog_ack[$key]);
} else {
$out[] = trim($c);
}
}
}
// Tack on any new files
foreach ($smd_prog_ack as $file) {
if ( ($file != $smd_prognostics_checksums) && file_exists($file) ) {
$content = smd_prognostics_prep_file($file);
$out[] = $file.': ('.( ($ignore) ? 'NULL' : md5($content) ).')';
}
}
$fh = fopen($smd_prognostics_checksums, "w");
fwrite($fh, join(n, $out));
fclose($fh);
smd_prognostics_self_hash();
$msg = gTxt('smd_prognostics_acked');
}
}
if ($csi && $smd_prog_ack) {
$msg = gTxt('smd_prognostics_csi_sent');
} elseif ($csi) {
$msg = gTxt('smd_prognostics_none_selected');
}
pagetop(gTxt('smd_prognostics_ttl_ack'), $msg);
list($nok, $miss, $added, $hashdown, $hashmod) = smd_do_prognostics(1);
$nok = is_array($nok) ? $nok : array();
$miss = is_array($miss) ? $miss : array();
$added = is_array($added) ? $added : array();
$hashmod = is_array($hashmod) ? $hashmod : array();
$errnum = count(array_merge($nok, $miss, $added, $hashmod));
$forensics = array();
$lform = 'Y-m-d H:i:s';
$med = '';
echo n. '<div class="txp-layout">'.
n. '<div class="txp-layout-4col">'.
n. '<h1 class="txp-heading">'.
n. gTxt('smd_prognostics_ttl_ack').
n. '</h1>'.
n. '</div>'.
n. '<div id="'.$smd_prognostics_event.'_control" class="txp-layout-2col">'.
n. smd_prognostics_button_bar('ack').
n. '</div>'.
n. '<div id="'.$smd_prognostics_event.'_container" class="txp-layout-1col">'.
n. '<form class="smd_prognostics-ack-form" name="longform" method="post" action="?event='.$smd_prognostics_event.a.'step=smd_prognostics_ack'.a.'smd_prognostics_suppress=1">'.
n. '<div class="txp-listtables">'.
n. startTable('', '', 'txp-list');
if ($errnum > 0) {
foreach ($hashmod as $naughty) {
$sel = in_array($naughty, $smd_prog_ack);
echo tr(td(checkbox('selected[]', $naughty, $sel), '', 'multi-edit').tda(gTxt('smd_prognostics_lbl_hashmod')).tda($naughty));
}
foreach ($nok as $naughty) {
$sel = in_array($naughty, $smd_prog_ack);
echo tr(td(checkbox('selected[]', $naughty, $sel), '', 'multi-edit').tda(gTxt('smd_prognostics_lbl_changed')).tda($naughty));
if ($sel) {
$fi = stat($naughty);
$forensics['nok'][] = smd_prognostics_forensic_output($naughty, $fi);
$forensics['files'][$naughty] = chunk_split(base64_encode(file_get_contents($naughty)));
}
}
foreach ($miss as $naughty) {
$sel = in_array($naughty, $smd_prog_ack);
echo tr(td(checkbox('selected[]', $naughty, $sel), '', 'multi-edit').tda(gTxt('smd_prognostics_lbl_missing')).tda($naughty));
if ($sel) {
$forensics['miss'][] = $naughty;
}
}
foreach ($added as $naughty) {
$sel = in_array($naughty, $smd_prog_ack);
echo tr(td(checkbox('selected[]', $naughty, $sel), '', 'multi-edit').tda(gTxt('smd_prognostics_lbl_added')).tda($naughty));
if ($sel) {
$fi = stat($naughty);
$forensics['added'][] = smd_prognostics_forensic_output($naughty, $fi);
$forensics['files'][$naughty] = chunk_split(base64_encode(file_get_contents($naughty)));
}
}
if ($smd_prog_ack && $prefs['logging'] != 'none') {
$detect = explode(',',get_pref('smd_prognostics_lastdetect', time()));
if (!isset($detect[1])) {
$detect[1] = $detect[0];
}
$rs = safe_rows('*', 'txp_log', "time BETWEEN '" . date($lform, ($detect[0] - $prefs['smd_prognostics_check_freq'])) . "' AND '" . date($lform, ($detect[1] + 5)) . "'");
foreach ($rs as $row) {
$forensics['txp_log'][] = join(',',$row);
}
}
$methods = array(
'acknowledge' => array('label' => gTxt('smd_prognostics_btn_ackit')),
'ignore' => array('label' => gTxt('smd_prognostics_btn_ignore')),
'csi' => array('label' => gTxt('smd_prognostics_btn_csi')),
);
$med = multi_edit($methods, $smd_prognostics_event, 'smd_prognostics_ack');
if (get_pref('smd_prognostics_mailto_csi', '') == '') {
unset($methods['csi']);
}
} else {
echo tr(td(gTxt('smd_prognostics_no_alarms')));
set_pref('smd_prognostics_lastdetect', '', 'smd_prognos', PREF_HIDDEN, 'text_input');
}
echo endTable().
'</div>'.
$med.
tInput().
'</form>'.
'</div></div>'.
script_js( <<<EOS
$(document).ready(function() {
$('.smd_prognostics-ack-form').txpMultiEditForm({
'row' : 'tr',
'highlighted' : 'tr'
});
});
EOS
);
if ($csi && $forensics) {
// Send the forensics off.
$to = get_pref('smd_prognostics_mailto_csi', '');
if ($to) {
$subject = gTxt('smd_prognostics_subject_csi', array('{site}' => get_pref('siteurl')));
$hdrs = smd_prognostics_header_info('smd_frognostics');
$body =
n.'Txp: ' . txp_version .n. 'PHP: ' . phpversion() .n. 'MySQL: ' . mysqli_get_server_info($DB->link) .n. ((is_callable('apache_get_version')) ? 'Apache: ' . apache_get_version().n : '').
((isset($forensics['nok'])) ? n.gTxt('smd_prognostics_preamble_nok').n.join(n,$forensics['nok']) : '').
((isset($forensics['miss'])) ? n.n.gTxt('smd_prognostics_preamble_miss').n.join(n,$forensics['miss']) : '').
((isset($forensics['added'])) ? n.n.gTxt('smd_prognostics_preamble_added').n.join(n,$forensics['added']) : '').
((isset($forensics['txp_log'])) ? n.n.gTxt('smd_prognostics_preamble_txplog').n.join(n,$forensics['txp_log']) : n.n.gTxt('smd_prognostics_no_log_entries'));
if (isset($forensics['files'])) {
$body .= n.n.gTxt('smd_prognostics_preamble_files');
foreach ($forensics['files'] as $fn => $content) {
$body .= n.n.$fn.n.n.$content.n;
}
}
mail($to, $subject, $body, $hdrs['headers']);
}
}
}
// ----------
function smd_prognostics_assign_var(&$target, $var)
{
$key = key($var);
if (is_array($var[$key])) {
smd_prognostics_assign_var($target[$key], $var[$key]);
} else {
if ($key == 0) {
$target[] = $var[$key];
} else {
$target[$key] = $var[$key];
}
}
}
// ----------
// File management
function smd_prognostics_files($msg = '')
{
global $smd_prognostics_event, $smd_prognostics_checksums;
$submit = 0;
// Pre-process the incoming 'data' blob back into $_POST variables.
// This bypasses the max_input_vars restriction when dealing with
// humungous arrays of values > 1000 rows.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['data'])) {
$vars = explode('&', $_POST['data']);
$data = array();
foreach ($vars as $var) {
parse_str($var, $variable);
smd_prognostics_assign_var($_POST, $variable);
}
$submit = 1;
}
$smd_prognostics_files = gps('smd_prognostics_files');
if (!is_array($smd_prognostics_files)) {
$smd_prognostics_files = array();
}
$adds = (strpos(get_pref('smd_prognostics_check_for'), 'add') !== false);
$filelist = smd_prognostics_readfiles();
$allcount = count($filelist);
if ($submit) {
$outfile = array();
foreach ($smd_prognostics_files as $file) {
$content = smd_prognostics_prep_file($file);
$outfile[] = $file.': ('.md5($content).')';
}
if (is_writable(dirname($smd_prognostics_checksums))) {
$fh = @fopen($smd_prognostics_checksums, "w");
if ($fh) {
fwrite($fh, join(n, $outfile));
if ($adds) {
$additions = array_diff($filelist, $smd_prognostics_files);
$added = array();
foreach ($additions as $addition) {
$added[] = $addition.': (NULL)';
}
fwrite($fh, n.join(n, $added));
}
fclose($fh);
smd_prognostics_self_hash();
smd_do_prognostics(2); // Silently acknowledge all the files
set_pref('smd_prognostics_lastdetect', '', 'smd_prognos', PREF_HIDDEN, 'text_input');
$msg = gTxt('smd_prognostics_files_updated');
} else {
$msg = array(gTxt('smd_prognostics_not_writable', array('{location}' => $smd_prognostics_checksums)), E_WARNING);
}
} else {
$msg = array(gTxt('smd_prognostics_not_writable', array('{location}' => dirname($smd_prognostics_checksums))), E_WARNING);
}
}
pagetop(gTxt('smd_prognostics_ttl_files'), $msg);
$smd_prognostics_files = array();
if ($cs = @file($smd_prognostics_checksums)) {
foreach ($cs as $c) {
if (preg_match('@^(\S+): \((.*)\)$@', trim($c), $m)) {
list(,$file,$md5) = $m;
if ($md5 != 'NULL') {
$smd_prognostics_files[] = $file;
}
}
}
}
$moncount = count($smd_prognostics_files);
if ($filelist) {
$filez = array();
foreach ($filelist as $key => $val) {
$filez[$val] = $filelist[$key];
}
$filesel = smd_prognostics_multisel('smd_prognostics_files', $filez, $smd_prognostics_files);
}
$showfiles = (!empty($filesel));
echo n. '<div class="txp-layout">'.
n. '<div class="txp-layout-2col">'.
n. '<h1 class="txp-heading">'.
n. gTxt('smd_prognostics_ttl_files').
n. '</h1>'.
n. '</div>'.
n. '<div id="'.$smd_prognostics_event.'_control" class="txp-layout-2col">'.
n. smd_prognostics_button_bar('fil').
n. '</div>'.
n. '<div id="'.$smd_prognostics_event.'_container" class="txp-layout-1col">'.
n. '<form class="smd_prognostics-files-form" method="post" action="?event='.$smd_prognostics_event.a.'step=smd_prognostics_files">'.
n. startTable('', '', 'txp-list').
n. tr(tdcs(gTxt('smd_prognostics_currmon', array('{curr}' => $moncount, '{outof}' => $allcount)) .(($showfiles) ? br.br. gTxt('smd_prognostics_monfiles_explain') : ''), 1, 400)).
n. (($showfiles) ? tr(tda($filesel)) : tr(tda(gTxt('smd_prognostics_no_files')))).
n. tr(tda(fInput('hidden', 'smd_prognostics_suppress', 1).fInput('submit', 'submit', gTxt('save'), 'publish'))).
n. endTable().
n. tInput().
n. '</form>'.
n. '</div></div>' . script_js(<<<EOJS
$(function() {
$('.smd_prognostics-files-form').submit(function(event) {
var me = $(this);
var data = me.serialize();
me.find("input, textarea, select, button").remove();
me.append("<input type='hidden' class='data' name='data' />");
me.find("input.data").val(data);
});
});
EOJS
);
}
// ----------
// Setup / prefs
function smd_prognostics_setup($msg = '')
{
global $smd_prognostics_event, $smd_prognostics_checksums, $prefs;
$origloc = get_pref('smd_prognostics_listloc', realpath(txpath.DS.'..'.DS).DS, 1);
$origexc = get_pref('smd_prognostics_excludir', 'images, files, tmp', 1);
$origdir = rtrim(get_pref('smd_prognostics_dir', realpath(txpath), 1), DS);
$origpfx = get_pref('smd_prognostics_prefix', '', 1);
$preflist = array(
'smd_prognostics_check_freq',
'smd_prognostics_check_qty',
'smd_prognostics_alarm_freq',
'smd_prognostics_check_where',
'smd_prognostics_mailto',
'smd_prognostics_mailto_csi',
'smd_prognostics_users',
'smd_prognostics_dir',
'smd_prognostics_prefix',
'smd_prognostics_listloc',
'smd_prognostics_excludir',
'smd_prognostics_ignores',
'smd_prognostics_inject_sensitivity',
'smd_prognostics_xss',
'smd_prognostics_txpdir',
);
$warnloc = '';
$notify = gps('smd_prognostics_notify_via');
$chfor = gps('smd_prognostics_check_for');
$reqs = gps('smd_prognostics_req_headers');
$sqlin = gps('smd_prognostics_sql_inject');
$tween = gps('smd_prognostics_check_between');
$rtfor = gps('smd_prognostics_rt_forensics');
// Only one of these valid status codes is allowed to be thrown
$throw_codes = array(
'smd_no' => gTxt('no'),
'smd_block' => gTxt('smd_prognostics_block'),
'200' => '200 OK',
'301' => '301 Moved Permanently',
'302' => '302 Found',
'307' => '307 Temporary Redirect',
'401' => '401 Unauthorized',
'403' => '403 Forbidden',
'404' => '404 Not Found',
'410' => '410 Gone',
'414' => '414 Request-URI Too Long',
'500' => '500 Internal Server Error',
'501' => '501 Not Implemented',
);
if (!is_array($tween)) {
$tween = array();
}
foreach ($tween as $idx => $val) {
if (empty($val)) {
$tween[$idx] = ($idx==0) ? '00:00' : '23:59';
} else {
$timeparts = do_list($val, ':');
foreach ($timeparts as $num) {
if (!is_numeric($num)) {
$tween[$idx] = ($idx==0) ? '00:00' : '23:59';
break;
}
}
}
}
$smd_prognostics_notify_via = join('|', ((is_array($notify)) ? $notify : array($notify)));
$smd_prognostics_check_for = join('|', ((is_array($chfor)) ? $chfor : array($chfor)));
$smd_prognostics_req_headers = join('|', ((is_array($reqs)) ? $reqs : array($reqs)));
$smd_prognostics_sql_inject = join('|', ((is_array($sqlin)) ? $sqlin : array($sqlin)));
$smd_prognostics_check_between = join('|', ((is_array($tween)) ? $tween : array($tween)));
$smd_prognostics_rt_forensics = join('|', ((is_array($rtfor)) ? $rtfor : array($rtfor)));
// Grab the saved pref values and tack on the array item(s)
extract(doSlash(gpsa(array_merge(array('submit'), $preflist))));
$preflist[] = 'smd_prognostics_notify_via';
$preflist[] = 'smd_prognostics_check_for';
$preflist[] = 'smd_prognostics_req_headers';
$preflist[] = 'smd_prognostics_sql_inject';
$preflist[] = 'smd_prognostics_check_between';
$preflist[] = 'smd_prognostics_rt_forensics';
$smd_prognostics_dir = rtrim($smd_prognostics_dir, DS);
if ($submit) {
if (($smd_prognostics_dir != $origdir) || ($smd_prognostics_prefix != $origpfx)) {
if (is_dir($smd_prognostics_dir) && is_writable($smd_prognostics_dir)) {
// Everything OK so do nothing for now
} else {
// Ignore new dir and reset it to what it was before
$msg = array(gTxt('smd_prognostics_not_writable', array('{location}' => $smd_prognostics_dir)), E_WARNING);
$smd_prognostics_dir = $origdir;
}
// Room for more config files as and when they are required
$filelist[] = $smd_prognostics_checksums;
foreach ($filelist as $file) {
$filename = $smd_prognostics_prefix.ltrim(basename($file), $origpfx);
rename($file, rtrim($smd_prognostics_dir, DS).DS.$filename);
}
}
// Write all the prefs
foreach ($preflist as $prefval) {
set_pref(doSlash($prefval), doSlash($$prefval), 'smd_prognos', PREF_HIDDEN, 'text_input');
}