/
check_auth_log
executable file
·1411 lines (1275 loc) · 45.7 KB
/
check_auth_log
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
#!/usr/bin/php -q
<?php
// check_auth_log
//
// Prevent malicious use of stolen email credentials to send large
// volumes of email through a postfix or exim mail server. This program parses
// sasl authentication info from mta log file and if configurable
// limits are exceeded blocks further sending.
//
// For installation instructions see file INSTALL.
// For usage instructions see file USAGE.
// For licensing see file LICENSE.
//
// Copyright 2010-2019 John Fawcett (john at voipsupport.it)
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
$version='3.2.1';
$copyright = 'check_auth_log version '.$version."\n".'Copyright 2010-2019 John Fawcett (john at voipsupport.it)'."\n".'Released under GPL v.3. There is no warranty';
$debug=false;
$opts=getopt('a:c:d:e:vtxyz');
// check_auth_log -v
// output version
if (isset($opts['v']))
{
echo $copyright."\n\n";
exit;
}
// check_auth_log -t
// activate tracing
if (isset($opts['t']))
{
echo $copyright."\n";
echo 'option t found, activating tracing'."\n";
$debug=true;
}
// check_auth_log -c<config_file>
// override default config file setting /etc/check_auth_log.conf
$configfile='';
if (isset($opts['c']))
{
$configfile=$opts['c'];
}
$conf = read_config($configfile);
if ($conf['syslog']) openlog('check_auth_log',LOG_PID,$conf['syslog_facility']);
output_message(LOG_INFO,'check_auth_log started');
// check_auth_log -d <saslusername>
// this re-enables mail sending
// If blocking method is access, then the saslusername is removed
// from the access file. If immediate activitation is required
// the access file should be postmapped and postfix reloaded
// If blocking method is mysql, then executes the unblock query.
if (isset($opts['d']))
{
$cached_vars=initialize($conf);
$cached_vars=open_db($conf,$cached_vars,'dbfile','rw');
switch($conf['block_type'])
{
case 'test':
break;
case 'mysql':
update_user_mysql($conf,$opts['d'],'unblock');
break;
case 'exim':
delete_exim_record($conf,$opts['d']);
break;
case 'access':
default:
delete_access_record($conf,$opts['d']);
break;
}
delete_db_record($conf,$cached_vars,$opts['d']);
output_message(LOG_INFO,'check_auth_log -d ended');
exit;
}
// check_auth_log -a <saslusername>
// this blockss mail sending
// If blocking method is access, then the saslusername is added to
// the access file. If immediate blocking is required
// the access file should be postmapped and postfix reloaded
// If blocking method is mysql, then executes the block query.
if (isset($opts['a']))
{
$cached_vars=initialize($conf);
$cached_vars=open_db($conf,$cached_vars,'dbfile','rw');
switch($conf['block_type'])
{
case 'test':
break;
case 'mysql':
update_user_mysql($conf,$opts['a'],'block');
break;
case 'exim':
add_exim_record($conf,$opts['a']);
break;
case 'access':
default:
add_access_record($conf,$opts['a']);
break;
}
output_message(LOG_INFO,'check_auth_log -a ended');
exit;
}
// check_auth_log -e
// test email
if (isset($opts['e']))
{
$cached_vars=initialize($conf);
notify_blocked_user($conf,$opts['e']);
output_message(LOG_INFO,'check_auth_log -e ended');
exit;
}
// check_auth_log -x
// extract database entries and print to standard output
if (isset($opts['x']))
{
$cached_vars=initialize($conf);
$cached_vars=open_db($conf,$cached_vars,'dbfile','r');
extract_db($conf,$cached_vars,'dbfile');
close_db($conf,$cached_vars,'dbfile');
output_message(LOG_INFO,'check_auth_log -x ended');
exit;
}
// check_auth_log -y
// extract cachefile entries and print to standard output
if (isset($opts['y']))
{
$cached_vars=initialize($conf);
$cached_vars=open_db($conf,$cached_vars,'cachefile','r');
extract_db($conf,$cached_vars,'cachefile');
close_db($conf,$cached_vars,'cachefile');
output_message(LOG_INFO,'check_auth_log -y ended');
exit;
}
// check_auth_log -z
// run self checks
if (isset($opts['z']))
{
$cached_vars=initialize($conf);
$cached_vars=open_db($conf,$cached_vars,'cachefile','r');
self_check($conf,$cached_vars);
close_db($conf,$cached_vars,'cachefile');
output_message(LOG_INFO,'check_auth_log -z ended. Unix timestamp='.time().' localtime='.date('YmdHis').' timezone='.date_default_timezone_get());
exit;
}
// if no -a -d -e -v -x -y -z option then do a normal run
$cached_vars=initialize($conf);
$cached_vars=open_db($conf,$cached_vars,'dbfile','rw');
$cached_vars=open_db($conf,$cached_vars,'cachefile','rw');
$cached_vars=self_check($conf,$cached_vars);
$cached_vars=read_previous_blocks($conf,$cached_vars);
$cached_vars=locate_next_line($conf,$cached_vars);
$cached_vars=process_rotated_log($conf,$cached_vars);
$cached_vars=process_log($conf,$cached_vars);
save_position($conf,$cached_vars);
save_self_check_info($conf,$cached_vars);
save_new_blocks($conf,$cached_vars);
close_log($conf,$cached_vars);
close_db($conf,$cached_vars,'dbfile');
close_db($conf,$cached_vars,'cachefile');
output_message(LOG_INFO,'check_auth_log ended. Unix timestamp='.time().' localtime='.date('YmdHis').' timezone='.date_default_timezone_get());
// set the configuration parameters.
function read_config($configfile)
{
global $debug;
if ($debug) echo 'start read_config'."\n";
if ($configfile=='')
$conf['configfile']='/etc/check_auth_log.conf';
else
$conf['configfile']=$configfile;
if ($debug) echo 'Using config file '.$conf['configfile']."\n";
// read config file
$ini=parse_ini_file($conf['configfile']);
$defaults=array(
'syslog'=>true,
'syslog_level'=>LOG_INFO,
'syslog_facility'=>LOG_MAIL,
'stdout'=>true,
'stdout_level'=>LOG_WARNING,
'mta'=>'postfix',
'logfile'=>'/var/log/mail.log',
'logfile_rotated'=>'',
'cachefile'=>'/tmp/.check_auth_log_cache_db',
'dbfile'=>'/tmp/.check_auth_log_db',
'dbtype'=>'db4',
'expire'=>3600,
'auth_limit'=>100,
'ip_limit'=>3,
'recipient_limit'=>0,
'max_auth_records'=>200,
'ignored_users'=>'',
'ignored_ips'=>'',
'posix'=>true,
'stale_lock_time'=>300,
'block_type'=>'mysql',
'sql_connect'=>'',
'sql_block'=>'',
'sql_unblock'=>'',
'accessfile'=>'/etc/postfix/smtp_auth_access.in',
'exim_block_file'=>'/tmp/blocklist',
'exim_temp_file'=>'/tmp/blocklist.out',
'self_check_enabled'=>true,
'self_check_last_match_warning_time'=>86400,
'self_check_last_log_warning_time'=>3600,
'self_check_mail_notify'=>false,
'log_tz_offset'=>0,
'admin_mail_sender'=>'',
'admin_mail_destination'=>'',
'notify_blocked_users'=>false,
'notify_block_email_template'=>'',
'notify_block_sender'=>'',
'reject_msg'=>'REJECT send quota exceeded. Contact support to re-enable');
foreach($ini as $k=>$v)
{
if ($debug)
echo "Ini file read ($k) value ($v)\n";
if (!isset($defaults[$k])) echo 'Warning ignoring unknown configuration setting '.$k."\n";
}
// set config values to ini values if present else defaults
foreach($defaults as $k=>$d)
{
if (isset($ini[$k])) $conf[$k]=$ini[$k]; else $conf[$k]=$d;
if ($debug) echo 'Variable ('.$k.') default ('.$d.') using ('.$conf[$k].")\n";
}
$conf['ignored_users_list']= ($conf['ignored_users']!='') ? explode(',',$conf['ignored_users']) : array();
if ($debug) echo 'Calculated variable (ignored_users_list) default () using ';
if ($debug) print_r($conf['ignored_users_list']);
$conf['ignored_ips_list']= ($conf['ignored_ips']!='') ? explode(',',$conf['ignored_ips']) : array();
if ($debug) echo 'Calculated variable (ignored_ips_list) default () using ';
if ($debug) print_r($conf['ignored_ips_list']);
return $conf;
}
// setup some variables used within the script and check for dba support or config errors
function initialize($conf)
{
global $debug;
output_message(LOG_DEBUG,'start initalize');
$cached_vars['ref_ts']=time();
if ($debug) echo 'time now is '. $cached_vars['ref_ts'].' (unix) = '.date('YmdHis',$cached_vars['ref_ts'])."\n";
if ($debug) echo 'default time zone '.date_default_timezone_get()."\n";
$cached_vars['access_changes']=false;
$cached_vars['rotated']=false;
$found=false;
if (!function_exists('dba_handlers')) output_message(LOG_CRIT,'This program requires the dba_handlers function from the php DBA extension. It may be in a package like php-dba. Please refer to the manual for your operating system distribution. Exiting');
if ($conf['self_check_enabled'] != true && $conf['self_check_enabled'] != false) output_message(LOG_CRIT,'Invalid self_check_enabled value of '.$conf['self_check_enabled'].'. Value must be true or false. Exiting');
if ($conf['self_check_mail_notify'] != true && $conf['self_check_mail_notify'] != false) output_message(LOG_CRIT,'Invalid self_check_mail_notify value of '.$conf['self_check_mail_notify'].'. Value must be true or false. Exiting');
if ($conf['self_check_mail_notify'] == true && $conf['admin_mail_sender'] == '') output_message(LOG_CRIT,'Invalid admin_mail_sender value of '.$conf['admin_mail_sender'].'. Exiting');
if ($conf['self_check_mail_notify'] == true && $conf['admin_mail_destination'] == '') output_message(LOG_CRIT,'Invalid admin_mail_destination value of '.$conf['admin_mail_destination'].'. Exiting');
if ($conf['self_check_last_match_warning_time'] < 1) output_message(LOG_CRIT,'Invalid self_check_last_match_warning_time. Cannot be less than 1.');
if ($conf['self_check_last_log_warning_time'] < 1) output_message(LOG_CRIT,'Invalid self_check_last_log_warning_time. Cannot be less than 1.');
if ($conf['syslog'] != true && $conf['syslog'] != false) output_message(LOG_CRIT,'Invalid syslog value of '.$conf['syslog'].'. Value must be true or false. Exiting');
if ($conf['syslog_level'] < LOG_EMERG || $conf['syslog_level'] > LOG_DEBUG) output_message(LOG_CRIT,'Invalid syslog_level. Exiting');
if ($conf['syslog_facility'] < LOG_KERN || $conf['syslog_facility'] > LOG_AUTHPRIV) output_message(LOG_CRIT,'Invalid syslog_facility. Exiting');
if ($conf['stdout'] != true && $conf['stdout'] != false) output_message(LOG_CRIT,'Invalid stdout value of '.$conf['stdout'].'. Value must be true or false. Exiting');
if ($conf['stdout_level'] < LOG_EMERG || $conf['stdout_level'] > LOG_DEBUG) output_message(LOG_CRIT,'Invalid stdout_level. Exiting');
if ($conf['posix'] != true && $conf['posix'] != false) output_message(LOG_CRIT,'Invalid posix value of '.$conf['posix'].'. Value must be true or false. Exiting');
if ($conf['posix'] && !function_exists('posix_kill')) output_message(LOG_CRIT,'This program requires the posix_kill function from the php posix extension. It may be in a package like php-process. Please refer to the manual for your operating system distribution. If you prefer you may disable posix code (used within pid locking) by setting configuration variable posix = false. Exiting');
foreach (dba_handlers() as $handler_name => $handler_version)
{
if ($conf['dbtype']==$handler_name) $found=true;
}
if (!$found) output_message(LOG_CRIT,'no support for db type '.$conf['dbtype'].' Exiting');
if ($conf['auth_limit'] > $conf['max_auth_records']) output_message(LOG_CRIT,'cannot set auth_limit higher than max_auth_records. Exiting');
if ($conf['ip_limit'] > $conf['max_auth_records']) output_message(LOG_CRIT,'cannot set ip_limit higher than max_auth_records. Exiting');
if ($conf['block_type'] !='mysql' && $conf['block_type'] !='access' && $conf['block_type'] !='exim' && $conf['block_type'] !='test') output_message(LOG_CRIT,'unknown value '.$conf['block_type'].'for block_type. Exiting');
if ($conf['block_type'] =='mysql' && ($conf['sql_connect']==''|| $conf['sql_block']==''||$conf['sql_unblock']=='')) output_message(LOG_CRIT,'set values for all of sql_connect sql_block and sql_unblock when block_type is mysql. Exiting');
if ($conf['block_type']=='exim' && !is_readable($conf['exim_block_file'])) output_message(LOG_CRIT,'Block file '.$conf['exim_block_file'].' is not readable. Exiting');
if ($conf['block_type']=='exim' && !is_writeable($conf['exim_block_file'])) output_message(LOG_CRIT,'Block file '.$conf['exim_block_file'].' is not writeable. Exiting');
if ($conf['block_type']=='access' && $conf['accessfile']=='') output_message(LOG_CRIT,'accessfile '.$conf['accessfile'].' cannot be blank. Exiting');
if ($conf['block_type']=='exim' && $conf['exim_temp_file']=='') output_message(LOG_CRIT,'exim_temp_file '.$conf['exim_temp_file'].' cannot be blank. Exiting');
if ($conf['mta'] !='postfix' && $conf['mta'] !='exim') output_message('unknown value '.$conf['mta'].'for mta. Exiting');
if ($conf['stale_lock_time'] < 0) output_message('Invalid stale_lock_time of '.$conf['stale_lock_time'].'. Value must be >= 0. Exiting');
if (count($conf['ignored_ips_list'])>0)
{
foreach($conf['ignored_ips_list'] as $net)
{
if (!validate_cidr($net)) output_message('Invalid cidr range specified for ignored_ips: '.$net.'. Exiting');
}
}
if ($conf['notify_blocked_users'] != true && $conf['notify_blocked_users'] != false) output_message(LOG_CRIT,'Invalid notify_blocked_users value of '.$conf['notify_blocked_users'].'. Value must be true or false. Exiting');
if ($conf['notify_blocked_users'] && $conf['notify_block_sender']=='') output_message(LOG_CRIT,'notify_block_sender must be set. Exiting');
if ($conf['notify_blocked_users'] && $conf['notify_block_email_template']=='') output_message(LOG_CRIT,'notify_block_email_template must be set. Exiting');
if ($conf['notify_blocked_users'])
{
$notify_email = file_get_contents($conf['notify_block_email_template']);
if ($notify_email =='') output_message(LOG_CRIT,'notify_block_email_template must be a file containing the subject and body for the notification email . Exiting');
}
$conf['queueid_map']=array();
return $cached_vars;
}
// open database used to store info of email authentications
function open_db($conf,$cached_vars,$db,$mode)
{
output_message(LOG_DEBUG,'start open_db '.$db.' '.$conf[$db]);
$open_mode='cd';
if ($mode=='rw') $open_mode='cdt';
if ($mode=='r') $open_mode='rdt';
if (!$dbh = dba_open($conf[$db],$open_mode,$conf['dbtype']))
{
output_message(LOG_ERR,'could not open database '.$conf[$db].' of type '.$conf['dbtype']);
output_message(LOG_ERR,'Available DBA handlers:');
foreach (dba_handlers(true) as $handler_name => $handler_version)
{
$handler_version = str_replace('$', '', $handler_version);
output_message(LOG_ERR,"- $handler_name: $handler_version");
}
output_message(LOG_CRIT,'Exiting due to previous error');
}
$cached_vars['dbh_'.$db]=$dbh;
output_message(LOG_DEBUG,'db opened '.$db.' '.$conf[$db]);
return $cached_vars;
}
// open log file and position file pointer at next unread line
function locate_next_line($conf,$cached_vars)
{
output_message(LOG_DEBUG,'start locate_next_line');
$cached_vars['rotated']=false;
$log_fh=fopen($conf['logfile'],'r') or output_message(LOG_CRIT,'could not open file '.$conf['logfile'].'. Exiting');
$firstline=fgets($log_fh);
$cached_vars['log_fh']=$log_fh;
$cached_vars['log_firstline']=$firstline;
// no previous cache file pos, set log stream position to start of log
$stored_firstline=dba_fetch('log_firstline',$cached_vars['dbh_cachefile']);
$stored_lastline=dba_fetch('log_lastline',$cached_vars['dbh_cachefile']);
$stored_pos=dba_fetch('log_pos',$cached_vars['dbh_cachefile']);
if(!$stored_pos || !$stored_lastline || !$stored_firstline)
{
$rc=fseek($log_fh,0);
if ($rc != 0) output_message(LOG_CRIT,'error positioning at start of log. Exiting');
return $cached_vars;
}
// no match with stored first line, the file is likely rotated
if ($firstline != $stored_firstline && $stored_firstline !='')
{
if ($conf['logfile_rotated']!='')
{
$conf=update_rotated_logfile_name($conf);
$log_fh_rot=fopen($conf['logfile_rotated'],'r') or output_message(LOG_CRIT,'could not open file '.$conf['logfile_rotated'].'. Exiting');
// set rotated log stream to last processed line
$offset=strlen($stored_lastline);
$pos=intval($stored_pos)-$offset;
$rc=fseek($log_fh_rot,$pos);
if ($rc != 0) output_message(LOG_CRIT,'error positioning at ['.$pos.'] in rotated log. Exiting');
$lastline=fgets($log_fh_rot);
if ($lastline!==false && $lastline == $stored_lastline)
{
$cached_vars['log_fh_rot']=$log_fh_rot;
$cached_vars['rotated']=true;
}
}
// set log stream position to start of log
$rc=fseek($log_fh,0);
if ($rc != 0) output_message(LOG_CRIT,'error positioning at start of log. Exiting');
return $cached_vars;
}
// set log stream to last processed line
$offset=strlen($stored_lastline);
$pos=intval($stored_pos)-$offset;
$rc=fseek($log_fh,$pos);
if ($rc != 0) output_message(LOG_CRIT,'error positioning at ['.$pos.'] in log. Exiting');
$lastline=fgets($log_fh);
if ($lastline===false || $lastline != $stored_lastline)
{
$rc=fseek($log_fh,0);
if ($rc != 0) output_message(LOG_CRIT,'error positioning at start of log. Exiting');
return $cached_vars;
}
return $cached_vars;
}
// substitute variables in log file name
function update_rotated_logfile_name($conf)
{
if (strpos($conf['logfile_rotated'],'YYYY')===FALSE)
{
$conf['logfile_rotated']=str_replace('YY',date('y'),$conf['logfile_rotated']);
}
else
{
$conf['logfile_rotated']=str_replace('YYYY',date('Y'),$conf['logfile_rotated']);
}
$conf['logfile_rotated']=str_replace('MM',date('m'),$conf['logfile_rotated']);
$conf['logfile_rotated']=str_replace('DD',date('d'),$conf['logfile_rotated']);
return $conf;
}
// process the log lines from current position to end of file
function process_log($conf,$cached_vars)
{
output_message(LOG_DEBUG,'start process_log');
$i=0;
while (!feof($cached_vars['log_fh']))
{
$line = fgets($cached_vars['log_fh']);
if ($line !== false)
{
$cached_vars['log_lastline']=$line;
$cached_vars=process_line($conf,$cached_vars,$line);
$i++;
}
}
$cached_vars['lines_read']=$i;
return $cached_vars;
}
// process the rotated log if needed
function process_rotated_log($conf,$cached_vars)
{
output_message(LOG_DEBUG,'start process_rotated_log');
if (!$cached_vars['rotated'])
return $cached_vars;
$i=0;
while (!feof($cached_vars['log_fh_rot']))
{
$line = fgets($cached_vars['log_fh_rot']);
if ($line !== false)
{
$cached_vars=process_line($conf,$cached_vars,$line);
$i++;
}
}
return $cached_vars;
}
// save info about last log position to cache file
function save_position($conf,$cached_vars)
{
output_message(LOG_DEBUG,'start save_position');
if ($cached_vars['lines_read']==0 && !$cached_vars['rotated']) return;
$pos=ftell($cached_vars['log_fh']);
if (!isset($cached_vars['log_lastline'])) $cached_vars['log_lastline']='';
dba_replace('log_firstline',$cached_vars['log_firstline'],$cached_vars['dbh_cachefile']) or output_message(LOG_CRIT,'cannot insert into db, key: log_firstline. Exiting');
dba_replace('log_lastline',$cached_vars['log_lastline'],$cached_vars['dbh_cachefile']) or output_message(LOG_CRIT,'cannot insert into db, key: log_lastline. Exiting');
dba_replace('log_pos',$pos,$cached_vars['dbh_cachefile']) or output_message(LOG_CRIT,'cannot insert into db, key: log_pos. Exiting');
}
// save info for self check
function save_self_check_info($conf,$cached_vars)
{
output_message(LOG_DEBUG,'start save_self_check_info');
if (isset($cached_vars['last_match_ts']))
dba_replace('last_match_ts',$cached_vars['last_match_ts'],$cached_vars['dbh_cachefile']) or output_message(LOG_CRIT,'cannot insert into db, key: last_match_ts. Exiting');
$last_log_ts=get_unix_ts_from_logline($conf,$cached_vars['log_lastline']);
dba_replace('last_log_ts',$last_log_ts,$cached_vars['dbh_cachefile']) or output_message(LOG_CRIT,'cannot insert into db, key: last_log_ts. Exiting');
}
// close log
function close_log($conf,$cached_vars)
{
fclose($cached_vars['log_fh']);
}
// close db
function close_db($conf,$cached_vars,$db)
{
dba_close($cached_vars['dbh_'.$db]);
}
// parse single log line, if it contains sasl authentication update database record and if limits exceeded apply block
function process_line($conf,$cached_vars,$line)
{
list($rc,$ret_type,$ret_array)=match_line($conf,$cached_vars,$line);
if ($rc)
{
switch($ret_type)
{
case 'num_recipients':
return process_num_recipients_line($conf,$cached_vars,$ret_array);
break;
case 'check_auth_log':
return process_check_auth_log_line($conf,$cached_vars,$ret_array);
break;
case 'login':
return process_login_line($conf,$cached_vars,$ret_array);
break;
default:
output_message(LOG_ERR, 'Unknown match type');
}
}
else
{
output_message(LOG_DEBUG, 'Not found');
}
return $cached_vars;
}
function process_login_line($conf,$cached_vars,$ret_array)
{
list($ip,$login,$unix_ts,$queueid)=$ret_array;
output_message(LOG_DEBUG,"Found ip $ip, login $login, ts $unix_ts, queue id $queueid");
$cached_vars['queueid_map'][$queueid]=$login;
// Update cached last timestamp variable (used for self check)
$cached_vars['last_match_ts'] = $unix_ts;
// if user should be ignored stop processing
if (array_search($login,$conf['ignored_users_list'],true)!==false)
{
output_message(LOG_NOTICE,'Ignoring user '.$login.' in ignored_users');
return $cached_vars;
}
// if ip should be ignored stop processing
if (in_iplist($ip,$conf['ignored_ips_list']))
{
output_message(LOG_NOTICE, 'Ignoring ip '.$ip.' in ignored_ips');
return $cached_vars;
}
// update db with login
$cur_val=dba_fetch($login,$cached_vars['dbh_dbfile']);
if ($cur_val === false)
{
$new_val= $ip.','.$unix_ts.','.$queueid.',0;';
$new_val=remove_expired($conf,$cached_vars,$new_val);
dba_insert($login,$new_val,$cached_vars['dbh_dbfile']) or output_message(LOG_CRIT,'cannot insert into db, key: '.$login.'. Exiting');
}
else
{
$new_val= $cur_val.$ip.','.$unix_ts.','.$queueid.',0;';
$new_val=remove_expired($conf,$cached_vars,$new_val);
dba_replace($login,$new_val,$cached_vars['dbh_dbfile']) or output_message(LOG_CRIT,'cannot replace in db, key: '.$login.'. Exiting');
}
$cached_vars=check_login_limit($conf,$cached_vars,$login,$new_val);
return $cached_vars;
}
function process_num_recipients_line($conf,$cached_vars,$ret_array)
{
list($queueid,$num_recipients)=$ret_array;
$login= isset($cached_vars['queueid_map'][$queueid]) ? $cached_vars['queueid_map'][$queueid] : '';
output_message(LOG_DEBUG,"Found number of receipients $num_recipients for queue id $queueid login $login");
if ($login=='') return $cached_vars;
// update db with number or recipients
$cur_val=dba_fetch($login,$cached_vars['dbh_dbfile']);
if ($cur_val === false)
{
}
else
{
$new_val=update_nrcpt($conf,$cached_vars,$cur_val,$queueid,$num_recipients);
dba_replace($login,$new_val,$cached_vars['dbh_dbfile']) or output_message(LOG_CRIT,'cannot replace in db, key: '.$login.'. Exiting');
}
$cached_vars=check_recipient_limit($conf,$cached_vars,$login,$new_val);
unset($cached_vars['queueid_map'][$queueid]);
return $cached_vars;
}
// parsing of the log lines delegated to this function in order to better manage support for multiple mtas
function process_check_auth_log_line($conf,$cached_vars,$ret_array)
{
global $debug;
list($ref_ts,$localtime,$timezone,$unix_ts)=$ret_array;
output_message(LOG_DEBUG,"Found ref_ts $ref_ts, localtime $localtime, timezone $timezone, ts $unix_ts");
$ts_diff = $ref_ts - $unix_ts;
if ($ts_diff > 5 || $ts_diff < -5)
{
output_message(LOG_ERR,'There is a difference between the log timestamps and the time calculated by the script of '.$ts_diff.'. This will prevent the script from working correctly. Please set/adjust log_tz_offset in check_auth_log.conf to/by a value near this difference.');
}
else
{
if ($debug) echo 'Difference between the log timestamps and the time calculated by the script of '.$ts_diff.'. OK'."\n";
}
return $cached_vars;
}
function match_line($conf,$cached_vars,$line)
{
output_message(LOG_DEBUG,'processing log line: '.$line);
switch($conf['mta'])
{
case 'exim':
$pattern='/^(\d+-\d+-\d+ \d+\:\d+\:\d+).*H=.* \[(\d+\.\d+\.\d+\.\d+)\] P=\w+.*A=\w+\:(\S*)/';
$rc = match_login_line($conf,$pattern,$line);
if ($rc !== false) return $rc;
break;
case 'postfix':
default:
# Feb 2 01:00:04 server02 postfix/submission/smtpd[18059]: 43rvH83Gwpz3wp4: client=a.b.ccc[1.2.3.4]:49099, sasl_method=LOGIN, sasl_username=aaaa@bbb.ccc
$pattern='/^(\S*\s*\S*\s*\S*)\s\S*\s\S*\s(\S*):\sclient=[^\[]*\[(\S*)\](?:\:\d+)?, sasl_method=\S*, sasl_username=(\S*)/';
$rc = match_login_line($conf,$pattern,$line);
if ($rc !== false) return $rc;
# Feb 2 11:04:36 server02 postfix/qmgr[9549]: 43s8hh4lvbz3wfm: from=<aaa@bbb.ccc>, size=3211, nrcpt=2 (queue active)
$pattern='/^(\S*\s*\S*\s*\S*)\s\S*\s\S*\s(\S*):\sfrom=\S*\ssize=\d+,\snrcpt=(\d+)\s\(queue\sactive\)/';
$rc = match_num_recipients_line($conf,$pattern,$line);
if ($rc !== false) return $rc;
#Feb 2 10:57:23 server02 check_auth_log[8333]: check_auth_log ended. Unix timestamp=1549101443 localtime=20190202105723 timezone=Europe/Rome
$pattern='/^(\S*\s*\S*\s*\S*)\s\S*\s\S*:\scheck_auth_log ended. Unix timestamp=(\d+) localtime=(\d+) timezone=(\S*)/';
$rc = match_check_auth_log_line($conf,$pattern,$line);
if ($rc !== false) return $rc;
break;
}
return array(false,'',array());
}
function match_login_line($conf,$pattern,$line)
{
$rc= preg_match($pattern, $line, $matches);
if($rc != 0)
{
if ($conf['mta']=='exim')
{
$ts_pos=1;
$ip_pos=2;
$login_pos=3;
$queueid='';
$dt = $matches[$ts_pos];
$unix_ts = get_unix_ts_normalized($conf,$dt);
}
if ($conf['mta']=='postfix')
{
$ts_pos=1;
$queueid_pos=2;
$ip_pos=3;
$login_pos=4;
$queueid=$matches[$queueid_pos];
$unix_ts = get_unix_ts($conf,$matches[$ts_pos]);
}
$ip=$matches[$ip_pos];
$login=$matches[$login_pos];
if ($unix_ts === false)
{
output_message (LOG_CRIT,'unable to convert string to timestamp. Exiting');
}
return array(true,'login',array($ip,$login,$unix_ts,$queueid));
}
return false;
}
function match_num_recipients_line($conf,$pattern,$line)
{
$rc= preg_match($pattern, $line, $matches);
if($rc != 0)
{
$ts_pos=1;
$queueid_pos=2;
$num_recipients_pos=3;
$queueid=$matches[$queueid_pos];
$num_recipients=$matches[$num_recipients_pos];
return array(true,'num_recipients',array($queueid,$num_recipients));
}
return false;
}
function match_check_auth_log_line($conf,$pattern,$line)
{
$rc= preg_match($pattern, $line, $matches);
if($rc != 0)
{
if ($conf['mta']=='exim')
{
$ts_pos=1;
$ref_ts_pos=2;
$localtime_pos=3;
$timezone_pos=4;
$ref_ts=$matches[$ref_ts_pos];
$localtime=$matches[$localtime_pos];
$timezone=$matches[$timezone_pos];
$dt = $matches[$ts_pos];
$unix_ts = get_unix_ts_normalized($conf,$dt);
}
if ($conf['mta']=='postfix')
{
$ts_pos=1;
$ref_ts_pos=2;
$localtime_pos=3;
$timezone_pos=4;
$ref_ts=$matches[$ref_ts_pos];
$localtime=$matches[$localtime_pos];
$timezone=$matches[$timezone_pos];
$unix_ts = get_unix_ts($conf,$matches[$ts_pos]);
}
if ($unix_ts === false)
{
output_message (LOG_CRIT,'unable to convert string to timestamp '.$dt.' (timestamp was: '.$matches[$ts_pos].')'.'. Exiting');
}
return array(true,'check_auth_log',array($ref_ts,$localtime,$timezone,$unix_ts));
}
return false;
}
// removes old authentication record
function remove_expired($conf,$cached_vars,$cur_val)
{
if ($cur_val=='') return '';
$new_val='';
$vals=explode(';',$cur_val);
if (count($vals) >= $conf['max_auth_records'])
{
array_shift($vals);
}
foreach($vals as $val)
{
if ($val != '')
{
list($ip,$unix_ts,$queueid,$num_recipients) = explode(',',$val);
if ($unix_ts+$conf['expire'] > $cached_vars['ref_ts']) $new_val.=$val.';';
}
}
return $new_val;
}
function update_nrcpt($conf,$cached_vars,$cur_val,$queueid,$num_recipients)
{
if ($cur_val=='') return '';
$new_val='';
$vals=explode(';',$cur_val);
foreach($vals as $val)
{
if ($val != '')
{
list($ip,$unix_ts,$cur_queueid,$cur_num_recipients) = explode(',',$val);
if ($cur_queueid==$queueid)
{
$new_num_recipients = $cur_num_recipients + $num_recipients;
$new_val.=$ip.','.$unix_ts.','.$cur_queueid.','.$new_num_recipients.';';
}
else
{
$new_val.=$val.';';
}
}
}
return $new_val;
}
// Checks if limits exceeded and applies block to username
function check_login_limit($conf,$cached_vars,$login,$new_val)
{
if ($new_val=='') return $cached_vars;
$ips=array();
$vals=explode(';',$new_val);
foreach($vals as $val)
{
if ($val != '')
{
list($ip,$unix_ts,$queueid,$num_recipients) = explode(',',$val);
$ips[]=$ip;
}
}
if (count($ips) ==0) return $cached_vars;
$unique_ips=array_unique($ips);
$login_count=count($vals);
$ip_count=count($unique_ips);
if ((($conf['auth_limit'] != 0 && $login_count > $conf['auth_limit']) || ($conf['ip_limit'] !=0 && $ip_count> $conf['ip_limit']))
&& !already_blocked($cached_vars,$login))
{
output_message(LOG_WARNING,'Blocking user: '.$login.' after '.$login_count.' logins from '.$ip_count.' ips in '.$conf['expire'].' seconds');
$cached_vars=block_user($conf,$cached_vars,$login);
}
return $cached_vars;
}
function check_recipient_limit($conf,$cached_vars,$login,$new_val)
{
if ($new_val=='') return $cached_vars;
$total_recipients=0;
$vals=explode(';',$new_val);
foreach($vals as $val)
{
if ($val != '')
{
list($ip,$unix_ts,$queueid,$num_recipients) = explode(',',$val);
$total_recipients+=$num_recipients;
}
}
if (($conf['recipient_limit'] != 0 && $total_recipients > $conf['recipient_limit'])
&& !already_blocked($cached_vars,$login))
{
output_message(LOG_WARNING,'Blocking user: '.$login.' after '.$total_recipients.' recipeints in '.$conf['expire'].' seconds');
$cached_vars=block_user($conf,$cached_vars,$login);
}
return $cached_vars;
}
// block user
function block_user($conf,$cached_vars,$login)
{
switch($conf['block_type'])
{
case 'test':
break;
case 'mysql':
update_user_mysql($conf,$login,'block');
break;
case 'exim':
add_exim_record($conf,$login);
break;
case 'access':
default:
add_access_record($conf,$login);
break;
}
$cached_vars['new_blocks'][]=$login;
$cached_vars['access_changes']=true;
if ($conf['notify_blocked_users'])
{
notify_blocked_user($conf,$login);
}
return $cached_vars;
}
// add postfix access record
function add_access_record($conf,$key)
{
if(!is_readable($conf['accessfile']))
file_put_contents($conf['accessfile'],'');
$in=file($conf['accessfile']);
$imax=count($in);
$i=0;
$found=false;
while($i<$imax)
{
$r=explode(' ',$in[$i]);
if($r[0]==$key)
{
$found=true;
$i=$imax;
}
$i++;
}
if (!$found)
{
$in[]=$key.' '.$conf['reject_msg']."\n";
file_put_contents($conf['accessfile'],implode('',$in));
output_message(LOG_WARNING,'Added '.$key.' to '.$conf['accessfile']);
}
else
{
output_message(LOG_WARNING,'Add failed: '.$key.' already in '.$conf['accessfile']);
}
}
// block user in mysql
function update_user_mysql($conf,$key,$mode)
{
$url=parse_url($conf['sql_connect']);
if ($url !== false && isset($url['scheme']) && $url['scheme']=='mysql')
{
if (isset($url['host']) && $url['host'] != '') $host=$url['host']; else output_message(LOG_CRIT,'No database hostname specified in url. Exiting');
if (isset($url['port']) && $url['port'] != '') $host .= ':'.$url['port'];
if (isset($url['user']) && $url['user'] != '') $user=$url['user']; else output_message(LOG_CRIT,'No database user specified in url. Exiting');
if (isset($url['pass']) && $url['pass'] != '') $password=$url['pass']; else output_message(LOG_CRIT,'No database password specified in url. Exiting');
if (isset($url['path']) && $url['path'] != '') $database=substr($url['path'],1); else output_message(LOG_CRIT,'No database password specified in url. Exiting');
if ($mode=='block')
$query = $conf['sql_block'];
else
$query = $conf['sql_unblock'];
$query = str_replace('%u', $key, $query);
$key_split = explode('@',$key);
$query = str_replace('%l', $key_split[0], $query);
$connection = mysql_connect($host,$user,$password)
or output_message(LOG_CRIT,'Could not connect: '.mysql_error().'. Exiting');
mysql_select_db($database,$connection)
or output_message(LOG_CRIT,'Error in selecting the database: '.mysql_error().'. Exiting');
$sql_result=mysql_query($query,$connection)
or output_message(LOG_CRIT,'Sql Error '.mysql_error().'. Exiting');
if(mysql_affected_rows($connection) == 1)
{
if ($mode=='block')
output_message(LOG_WARNING,'Disabled '.$key.' in mysql database');
else
output_message(LOG_WARNING,'Enabled '.$key.' in mysql database');
}
else
{
output_message(LOG_WARNING,$mode.' query did not change mysql database');
}
}
else
{
output_message(LOG_CRIT,'could not parse sql connect string '.$conf['sql_connect'].'. Exiting');
}
}
// add exim block record
function add_exim_record($conf,$key)
{
$in=file($conf['exim_block_file']);
$imax=count($in);
$i=0;
$found=false;
while($i<$imax)
{
$r=explode(' ',$in[$i]);
if($r[0]==$key)
{
$found=true;
$i=$imax;
}
$i++;
}
if (!$found)
{
$in[]=$key."\n";
file_put_contents($conf['exim_temp_file'],implode('',$in));
$rc=rename($conf['exim_temp_file'],$conf['exim_block_file']);
if ($rc===false)
output_message(LOG_ERR,'Failed to rename '.$conf['exim_temp_file'].' to '.$conf['exim_block_file']);
else
output_message(LOG_WARNING,'Added '.$key.' to '.$conf['exim_block_file']);
}
else
{
output_message(LOG_ERR,'Add failed: '.$key.' already in '.$conf['exim_block_file']);
}
}
// delete postfix access record
function delete_access_record($conf,$key)
{
if(!is_readable($conf['accessfile'])) output_message(LOG_CRIT,"cannot open access file ".$conf['accessfile'].'. Exiting');
$in=file($conf['accessfile']);
$imax=count($in);