-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgreyldap
executable file
·1491 lines (1179 loc) · 48 KB
/
postgreyldap
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/perl -T -w
# PostgreyLDAP: an LDAP backed Postfix Greylisting Policy Server
# Copyright (c) 2004-2007 ETH Zurich
# Copyright (c) 2007 Open Systems AG, Switzerland
# Copyright (c) 2012 Jeff Warnica
# released under the GNU General Public License
# see the documentation with 'perldoc postgreyldap'
package postgreyldap;
use strict;
use Pod::Usage;
use Getopt::Long 2.25 qw(:config posix_default no_ignore_case);
use Net::Server; # used only to find out which version we use
use Net::Server::Multiplex;
use Net::LDAP;
use DBI;
use Fcntl ':flock'; # import LOCK_* constants
use Sys::Hostname;
use Sys::Syslog; # used only to find out which version we use
use POSIX qw(strftime setlocale LC_ALL floor);
use Time::HiRes qw ( setitimer ITIMER_VIRTUAL ITIMER_REAL );
use Config::Simple;
use Data::Dumper;
use vars qw(@ISA);
@ISA = qw(Net::Server::Multiplex);
my $VERSION = '0.0.1';
my $DEFAULT_LOCKDIR = '/var/spool/postfix/postgrey';
my $CONFIG_DIR = '/etc/postfix';
sub unix2generalizedTime($$) {
my ($self, $in) = @_;
return strftime("%Y%m%d%k%M%SZ", localtime($in));
}
sub generalizedTime2UnixTime($$) {
my ($self, $in) = @_;
$self->mylog(3, ">> generalizedTime2UnixTime( $in)");
my ($year, $month, $day, $hour, $min, $sec, $frac, $local, $offdir, $offhr, $offmin, $time);
$frac = 0;
$local = 0;
if ($in =~ /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)\.?(\d\d\d)?$/) {
($year, $month, $day, $hour, $min, $sec) = ($1, $2, $3, $4, $5, $6);
if (defined $7) { $frac = $7;}
$self->mylog(5, " local: ($year, $month, $hour, $min, $sec, $frac) ");
$local = 1;
} elsif ($in =~ /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)\.?(\d\d\d)?Z$/) {
($year, $month, $day, $hour, $min, $sec) = ($1, $2, $3, $4, $5, $6);
if (defined $7) { $frac = $7;}
$self->mylog(5, " UTC: ($year, $month, $hour, $min, $sec, $frac) ");
} elsif ($in =~ /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)\.?(\d\d\d)?([+-])(\d\d)(\d\d)$/) {
($year, $month, $day, $hour, $min, $sec, $frac, $offdir, $offhr, $offmin) = ($1, $2, $3, $4, $5, $6, $7, $8, $9);
$self->mylog(5, " With offset: ($year, $month, $hour, $min, $sec, $frac, $offdir, $offhr, $offmin) ");
}
#(sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = -1)
$time = POSIX::mktime($sec, $min, $hour, $day, $month-1, $year-1900);
return $time;
}
sub ldap_init($)
{
my ($self) = @_;
$self->mylog(3, ">> ldap_init( )");
my $Config = $self->{pgl}{config};
$self->{pgl}{ldap} = Net::LDAP->new($Config->param('server')) or die "$@";
my $mesg = $self->{pgl}{ldap}->bind($Config->param('dn'), password => $Config->param('password')) || die "$@";
$mesg->code && die"failed to Bind to LDAP: ", $mesg->error ;
}
sub ldap_cawl_cleanup($$) {
my ($self, $max_age_t) = @_;
$self->mylog(3, ">> ldap_cawl_cleanup( $max_age_t )");
my $base = $self->{pgl}{ldap_base};
$max_age_t = $self->unix2generalizedTime($max_age_t);
my $result = $self->{pgl}{ldap}->search (
base => $base,
scope => "sub",
filter => "(&(objectClass=GreyListClientAutoWhitelist)(PostgreyLdapTimestampLast<=$max_age_t))",
attrs => ['dn']
); # || die "$@";
if ($result->code) {
warn "failed to cleanup: ", $result->error ;
return;
}
my $max = $result->count;
for ( my $i = 0 ; $i < $max ; $i++ ) {
my $entry = $result->entry ( $i );
$self->mylog(1, " Deleting entry " . $entry->dn());
$entry->delete();
$entry->update($self->{pgl}{ldap});
}
}
sub ldap_cawl_create($$) {
my ($self, $cawl_key, $cawl_count, $cawl_first_t, $now) = @_;
$cawl_first_t = defined($cawl_first_t ? $cawl_first_t : $now);
$self->mylog(3, ">> ldap_cawl_create( $cawl_key, $cawl_count, $cawl_first_t, $now )");
my $base = $self->{pgl}{ldap_base};
$now = $self->unix2generalizedTime($now);
$cawl_first_t = $self->unix2generalizedTime($cawl_first_t);
my $dn = "cn=" . $cawl_key . "," . $base;
$self->mylog(1, " Attempting to add cawl dn: $dn");
my $result = $self->{pgl}{ldap}->add(
$dn,
attr => [
'objectClass' => [ "top", "GreyListClientAutoWhitelist"],
'cn' => $cawl_key,
'PostgreyLdapClientHost' => $cawl_key,
'PostGreyLdapPassCount' => $cawl_count,
'PostgreyLdapTimestampFirst' => $cawl_first_t,
'PostgreyLdapTimestampLast' => $now,
#TODO add delta_t
]);
$result->code && warn "failed to add entry: ", $result->error ;
}
sub ldap_cawl_lookup($$) {
my ($self, $cawl_key) = @_;
$self->mylog(3, ">> ldap_cawl_lookup( $cawl_key )");
my $base = $self->{pgl}{ldap_base};
my $filter = "(&(objectClass=GreyListClientAutoWhitelist)(PostgreyLdapClientHost=$cawl_key))";
$self->mylog(4, " $base");
$self->mylog(4, " $filter");
my $result = $self->{pgl}{ldap}->search (
base => $base,
scope => "sub",
filter => $filter,
attrs => ['PostGreyLdapPassCount','PostgreyLdapTimestampLast']
);# || die "$@";
if ($result->code) {
warn "failed to do cawl lookup: ", $result->error ;
return;
}
$self->mylog(1, "Count: " . $result->count);
if ( $result->count > 1 ) {
die "Serious problems with LDAP: returning multiple results for $filter at $base. Should not be possible";
} elsif ( $result->count == 1 ) {
my $entry = $result->entry(0);
my $pc = $entry->get_value('PostGreyLdapPassCount');
my $tsl = $self->generalizedTime2UnixTime($entry->get_value('PostgreyLdapTimestampLast'));
$self->mylog(4, "<< $pc, $tsl");
return ($pc, $tsl, $entry);
} else {
return;
}
}
#note we are passed back the LDAP entry $cawl_entry from the search
sub ldap_cawl_update($$) {
#UPDATE cawl SET count=?, first_t=?, last_t=? WHERE ip=?
my ($self, $cawl_count, $now, $cawl_key, $cawl_first_t, $cawl_entry) = @_;
$cawl_first_t = defined($cawl_first_t ? $cawl_first_t : $now);
$self->mylog(3, ">> ldap_cawl_update( $cawl_count, $now, $cawl_key, $cawl_first_t, " . $cawl_entry->dn() . " )");
$now = $self->unix2generalizedTime($now);
$cawl_first_t = $self->unix2generalizedTime($cawl_first_t);
my $result = $self->{pgl}{ldap}->modify(
$cawl_entry->dn(),
changes => [
replace => [ 'PostGreyLdapPassCount', $cawl_count,
'PostgreyLdapTimestampLast', $now,
'PostgreyLdapTimestampFirst', $cawl_first_t
]
]);
}
#note we are passed back the LDAP entry $cawl_entry from the search
sub ldap_cawl_update2($$) {
#UPDATE cawl SET count=?, last_t=? WHERE ip=?
my ($self, $cawl_count, $now, $cawl_key, $cawl_entry) = @_;
$self->mylog(3, ">> ldap_cawl_update2( $cawl_count, $now, $cawl_key, " . $cawl_entry->dn() . " )");
my $nowAsLDAP = $self->unix2generalizedTime($now);
my $result = $self->{pgl}{ldap}->modify(
$cawl_entry->dn(),
changes => [
replace => [ 'PostGreyLdapPassCount', $cawl_count,
'PostgreyLdapTimestampLast', $nowAsLDAP
]
]);
}
sub ldap_triplet_lookup($$) {
my ($self, $client_net, $sender, $recip) = @_;
$self->mylog(3, ">> ldap_triplet_lookup( $client_net, $sender, $recip )");
my $filter = "(&(objectClass=GreyListTriplet)(PostgreyLdapClientAddress=$client_net)(PostgreyLdapSenderAddress=$sender)(PostgreyLdapRecipientAddress=$recip))";
my $base = $self->{pgl}{ldap_base};
$self->mylog(4, " $filter");
my $result = $self->{pgl}{ldap}->search (
base => $base,
scope => "sub",
filter => $filter,
attrs => ['PostgreyLdapTimestampFirst','PostgreyLdapTimestampLast']
);# || die "$@";
if ($result->code) {
warn "failed to do triplet lookup: ", $result->error ;
return;
}
my $resStruct = $result->entry(0);
$self->mylog(4, "Count: " . $result->count);
$self->mylog(2, "Searched for ( $client_net, $sender, $recip ). Result count: " . $result->count);
if ( $result->count > 1 ) {
die "Serious problems with LDAP: returning multiple results for $filter at $base. Should not be possible";
} elsif ( $result->count == 1 ) {
my $entry = $result->entry(0);
my $first = $self->generalizedTime2UnixTime($entry->get_value('PostgreyLdapTimestampFirst'));
my $last = $self->generalizedTime2UnixTime($entry->get_value('PostgreyLdapTimestampLast'));
$self->mylog(3, "<< $first, $last");
return ($first, $last, $entry);
} else {
return;
}
}
sub ldap_triplet_create($$) {
my ($self, $client_net, $sender, $recip, $client_host, $first, $now, $delta_t) = @_;
$self->mylog(3, ">> ldap_triplet_create( $client_net, $sender, $recip, $client_host, $first, $now, $delta_t )");
my $base = $self->{pgl}{ldap_base};
$first = $self->unix2generalizedTime($first);
$now = $self->unix2generalizedTime($now);
my $cn = "$client_net/$sender/$recip";
my $dn = "cn=" . $cn . "," . $base;
$self->mylog(4, " Attempting to add triplet dn: $dn");
my $result = $self->{pgl}{ldap}->add(
$dn,
attr => [
'objectClass' => [ "top", "GreyListTriplet"],
'cn' => $cn,
'PostgreyLdapClientAddress' => $client_net,
'PostgreyLdapSenderAddress' => $sender,
'PostgreyLdapRecipientAddress' => $recip,
'PostgreyLdapClientHost' => $client_host,
'PostgreyLdapTimestampFirst' => $first,
'PostgreyLdapTimestampLast' => $now,
'PostgreyTimestampDelta' => $delta_t,
]);
$result->code && warn "failed to add entry: ", $result->error ;
}
#UPDATE triplets SET host=?, first_t=?, last_t=?, delta_t=?
# WHERE ip=? AND send=? AND rcpt=?
sub ldap_triplet_update($$) {
my ($self, $client_host, $first, $now, $delta_t, $client_net, $sender, $recip, $trip_entry) = @_;
$self->mylog(3, ">> ldap_triplet_update( $client_host, $first, $now, $delta_t, $client_net, $sender, $recip, " . $trip_entry->dn() . " )");
my $base = $self->{pgl}{ldap_base};
my $dn = $trip_entry->dn();
$first = $self->unix2generalizedTime($first);
$now = $self->unix2generalizedTime($now);
$self->mylog(4, " Attempting to update triplet dn: $dn. PostgreyLdapClientHost: $client_host; PostgreyLdapTimestampFirst: $first; PostgreyLdapTimestampLast: $now; PostgreyTimestampDelta: $delta_t");
my $result = $self->{pgl}{ldap}->modify(
$dn,
changes => [
replace => [ 'PostgreyLdapClientHost', $client_host,
'PostgreyLdapTimestampFirst', $first,
'PostgreyLdapTimestampLast', $now,
'PostgreyTimestampDelta' => floor($delta_t),
]
]
);
$result->code && warn "failed to update entry: ", $result->error ;
}
sub ldap_triplets_cleanup($$) {
my ($self, $max_age_t, $retry_window_t) = @_;
$self->mylog(3, ">> ldap_triplets_cleanup( $max_age_t, $retry_window_t )");
my $base = $self->{pgl}{ldap_base};
$max_age_t = $self->unix2generalizedTime($max_age_t);
$retry_window_t = $self->unix2generalizedTime($retry_window_t);
my $delay = $self->{pgl}{delay};
my $filter = "(&(objectClass=GreyListTriplet)(|(PostgreyLdapTimestampLast<=$max_age_t)(&(PostgreyTimestampDelta<=$delay)(PostgreyLdapTimestampLast<=$retry_window_t))))";
$self->mylog(4, " Filter: $filter");
my $result = $self->{pgl}{ldap}->search (
base => $base,
scope => "sub",
filter => $filter,
attrs => ['dn']
);# || die "$@";
if ($result->code) {
warn "failed to do triplet cleanup: ", $result->error ;
return;
}
my $max = $result->count;
for ( my $i = 0 ; $i < $max ; $i++ ) {
my $entry = $result->entry ( $i );
$self->mylog(3, " Deleting entry " . $entry->dn());
$entry->delete();
$entry->update($self->{pgl}{ldap});
}
}
sub cidr_parse($)
{
defined $_[0] or return undef;
$_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)\/(\d+)$/ or return undef;
$1 < 256 and $2 < 256 and $3 < 256 and $4 < 256 and $5 <= 32 and $5 > 0
or return undef;
my $net = ($1 << 24)+($2 << 16)+($3 << 8)+$4;
my $mask = ~((1<<(32-$5))-1);
return ($net & $mask, $mask);
}
sub cidr_match($$$)
{
my ($net, $mask, $addr) = @_;
return undef unless defined $net and defined $mask and defined $addr;
if($addr =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) {
$addr = ($1 << 24)+($2 << 16)+($3 << 8)+$4;
}
return ($addr & $mask) == $net;
}
sub read_clients_whitelists($)
{
my ($self) = @_;
$self->mylog(3, ">> read_clients_whitelists( )");
my @whitelist_clients = ();
my @whitelist_ips = ();
my @whitelist_cidr = ();
for my $f (@{$self->{pgl}{whitelist_clients_files}}) {
my @lines;
$self->mylog(3, "\t Whitelist' file': $f");
if ($f eq "LDAP") {
@lines = $self->slurp_ldap_wl_clients();
$self->mylog(3, "slurp_ldap_wl_recip returned something of size: " . @lines);
} else {
$self->mylog(3, "\t reading Whitelist file: $f");
if (open(INPUT, "<$f")) {
(@lines) = <INPUT>;
$self->mylog(3, " File slurp read in the following number of lines: " . @lines);
close(INPUT);
} else {
# do not warn about .local file: maybe the user just doesn't have one
warn "can't open $f: $!\n"; # unless $f =~ /\.local$/;
}
}
foreach (@lines) {
s/#.*$//; s/^\s+//; s/\s+$//; next if $_ eq '';
if(/^\/(\S+)\/$/) {
# regular expression
push @whitelist_clients, qr{$1}i;
} elsif(/^@?\d{1,3}(?:\.\d{1,3}){0,3}$/) {
#our whitelist files could have entries like @12.34.56.78. Clearly they are IPs.
s/^@//;
# IP address or part of it
push @whitelist_ips, qr{^\Q$_\E\b};
} elsif(/^.*\:.*\:.*$/) {
# IPv6?
push @whitelist_ips, qr{^\Q$_\E\b};
} elsif(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}$/) {
my ($net, $mask) = cidr_parse($_);
if(defined $mask) {
push @whitelist_cidr, [ $net, $mask ];
} else {
warn "$f line $.: invalid cidr address\n";
}
} elsif(/^\S+$/) {
# note: we had ^[^\s\/]+$ but it triggers a bug in perl 5.8.0
push @whitelist_clients, qr{(?:^|\.)\Q$_\E$}i;
} else {
warn "$f line $.: doesn't look like a hostname\n";
}
}
}
$self->mylog(3, " whitelist_clients, whitelist_ips, whitelist_cidr are sized: " . @whitelist_clients . ", " . @whitelist_ips . ", " . @whitelist_cidr);
$self->{pgl}{whitelist_clients} = \@whitelist_clients;
$self->{pgl}{whitelist_ips} = \@whitelist_ips;
$self->{pgl}{whitelist_cidr} = \@whitelist_cidr;
}
sub slurp_ldap_wl_clients(@) {
my ($self) = @_;
my $attr = "PostgreyWhitelistEntry";
my $oc = "GreyListClientWhitelist";
return $self->slurp_ldap_wl_($oc, $attr);
}
sub slurp_ldap_wl_recip(@) {
my ($self) = @_;
my $attr = "PostgreyWhitelistEntry";
my $oc = "GreyListRecipientWhitelist";
return $self->slurp_ldap_wl_($oc, $attr);
}
sub slurp_ldap_wl_($$) {
my ($self, $oc, $attr) = @_;
$self->mylog(3, ">> slurp_ldap_wl_( $oc, $attr)");
my $filter = "(objectClass=$oc)";
my $base = $self->{pgl}{ldap_base};
$self->mylog(1, " $filter $base");
my $result = $self->{pgl}{ldap}->search (
base => $base,
scope => "sub",
filter => $filter,
attrs => [$attr]
);# || die "$@";
if ($result->code) {
warn "failed to do LDAP slurp of $oc : ", $result->error ;
return;
}
my @recips;
foreach ($result->entries()) {
push @recips, $_->get_value('PostgreyWhitelistEntry');
}
return @recips;
}
sub read_recipients_whitelists($)
{
my ($self) = @_;
$self->mylog(3, ">> read_recipients_whitelists( )");
my @whitelist_recipients = ();
for my $f (@{$self->{pgl}{whitelist_recipients_files}}) {
my @recips;
$self->mylog(3, "\t Whitelist' file': $f");
if ($f eq "LDAP") {
@recips = $self->slurp_ldap_wl_recip();
$self->mylog(3, "slurp_ldap_wl_recip returned something of size: " . @recips);
} else {
if (open(INPUT, "<$f")) {
(@recips) = <INPUT>;
close(INPUT);
} else {
# do not warn about .local file: maybe the user just doesn't have one
warn "can't open $f: $!\n" unless $f =~ /\.local$/;
}
}
foreach (@recips) {
$self->mylog(3, "Trying ty slurp entry: $_");
s/#.*$//; s/^\s+//; s/\s+$//; next if $_ eq '';
my ($user, $domain) = split(/\@/, $_, 2);
if(/^\/(\S+)\/$/) {
# regular expression
push @whitelist_recipients, qr{$1}i;
} elsif(!/^\S+$/) {
warn "$f line $.: doesn't look like an address\n";
}
# postfix access(5) syntax:
elsif(defined $domain and $domain ne '') {
# user@domain (match also user+extension@domain)
push @whitelist_recipients, qr{^\Q$user\E(?:\+[^@]+)?\@\Q$domain\E$}i;
} elsif(defined $domain) {
# user@
push @whitelist_recipients, qr{^\Q$user\E(?:\+[^@]+)?\@}i;
} else {
# domain ($user is the domain)
push @whitelist_recipients, qr{(?:^|\.)\Q$user\E$}i;
}
}
}
$self->{pgl}{whitelist_recipients} = \@whitelist_recipients;
}
sub do_sender_substitutions($$)
{
my ($self, $addr) = @_;
my ($user, $domain) = split(/@/, $addr, 2);
defined $domain or return $addr;
# strip extension, used sometimes for mailing-list VERP
$user =~ s/\+.*//;
# replace numbers in VERP addresses with '#' so that
# we don't create a new key for each mail
$user =~ s/\b\d+\b/#/g;
return "$user\@$domain";
}
# split network and host part and return both
sub do_client_substitutions($$$)
{
my ($self, $ip, $revdns) = @_;
if($self->{pgl}{lookup_by_host}) {
return ($ip, $ip);
}
my @ip=split(/\./, $ip);
return ($ip, undef) unless defined $ip[3];
# skip if it contains the last two IP numbers in the hostname
# (we assume it is a pool of dialup addresses of a provider)
return ($ip, undef) if $revdns =~ /$ip[2]/ and $revdns =~ /$ip[3]/;
return (join('.', @ip[0..2], '0'), $ip[3]);
}
sub ldap_check_and_reconnect($){
my $self = shift;
$self->log(3, "> ldap_check_and_reconnect()");
my $base = $self->{pgl}{ldap_base};
$self->log(4, "self->{ldap_retryCount} = " . $self->{pgl}{ldap_retryCount});
#first time, just test
if ($self->{pgl}{ldap_retryCount} == 0) {
my $result = $self->{pgl}{ldap}->search (
base => $base,
scope => "one",
filter => "(objectClass=*)",
attrs => ['dn']
) ;
#and return if all is OK.
if (!$result->code()) {
return;
}
}
$self->log(1, "Retry LDAP connection... : " . $self->{pgl}{ldap_retryCount});
#if we are busted, or retrying... retry
my $Config = $self->{pgl}{config};
my $mesg;
for (my $i=0; $i<=5; $i++){
$self->{pgl}{ldap} = Net::LDAP->new($Config->param('server')) or next;
$mesg = $self->{pgl}{ldap}->bind($Config->param('dn'), password => $Config->param('password'));
if (!$mesg->code) {
$self->{pgl}{ldap_retryCount} = 0;
$self->log(1, "Retry LDAP connection... Success! Yay. Back in business");
return;
}
}
if (++$self->{pgl}{ldap_retryCount} > 5) {
$self->log(1, "LDAP Server went away? Was unable to reconnect after 5 tries");
die("LDAP Server went away? Was unable to reconnect after 5 tries");
}
}
sub do_maintenance($$)
{
my ($self, $now) = @_;
$self->mylog(3, ">> dp_maintenance( $now )");
my $max_age_t = $now - $self->{pgl}{max_age};
my $retry_window_t = $now - $self->{pgl}{config}->param("retry-window");
# remove old triplets
$self->ldap_triplets_cleanup($max_age_t, $retry_window_t);
# remove old cawl entries
$self->ldap_cawl_cleanup($max_age_t);
}
sub mylog($$$)
{
my ($self, $level, $string) = @_;
$string =~ s/\%/%%/g; # for Net::Server <= 0.87
if(!defined $Sys::Syslog::VERSION or $Sys::Syslog::VERSION lt '0.15'
or !defined $Net::Server::VERSION or $Net::Server::VERSION lt '0.94') {
# Workaround for a crash when syslog daemon is temporarily not
# present (for example on syslog rotation).
# Note that this is not necessary with Sys::Syslog >= 0.15 and
# Net::Server >= 0.94 thanks to the nofatal Option.
eval {
local $SIG{"__DIE__"} = sub { };
$self->log($level, $string);
};
}
else {
$self->log($level, $string);
}
}
sub mylog_action($$$;$$)
{
my ($self, $attr, $action, $reason, $additional_info) = @_;
my $str;
$str .= $attr->{queue_id} . ': ' if $attr->{queue_id};
my @info = ("action=$action");
push @info, "reason=$reason" if defined $reason;
push @info, $additional_info if defined $additional_info;
for my $a (qw(client_name client_address sender recipient)) {
push @info, "$a=$attr->{$a}" if $attr->{$a};
}
$str .= join(', ', @info);
$self->mylog(2, $str);
}
sub is_new_instance($$)
{
my ($self, $inst) = @_;
return 1 if not defined $inst; # in case the 'instance' parameter
# was not supplied by the client (Exim)
# we keep a list of the last 20 "instances", which identify unique messages
# so that for example we only put one X-Greylist header per message.
$self->{pgl}{instances} = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
unless defined $self->{pgl}{instances};
my $i = $self->{pgl}{instances};
return 0 if scalar grep { $_ eq $inst } @$i;
# put new value into the array
unshift @$i, $inst;
pop @$i;
return 1;
}
# main routine: based on attributes specified as argument, return policy decision
sub smtpd_access_policy($$)
{
my ($self, $now, $attr) = @_;
$self->mylog(3, ">> smtpd_access_policy( $now, $attr )");
# This attribute occurs in connections from the policy-test script,
# not in a regular postfix query connection
$now = $attr->{policy_test_time} if defined $attr->{policy_test_time};
# whitelists
for my $w (@{$self->{pgl}{whitelist_clients}}) {
if($attr->{client_name} =~ $w) {
$self->mylog_action($attr, 'pass', 'client whitelist');
return 'DUNNO';
}
}
for my $w (@{$self->{pgl}{whitelist_ips}}) {
if($attr->{client_address} =~ $w) {
$self->mylog_action($attr, 'pass', 'client whitelist');
return 'DUNNO';
}
}
for my $w (@{$self->{pgl}{whitelist_cidr}}) {
if(cidr_match($w->[0], $w->[1], $attr->{client_address})) {
$self->mylog_action($attr, 'pass', 'client whitelist');
return 'DUNNO';
}
}
for my $w (@{$self->{pgl}{whitelist_recipients}}) {
if($attr->{recipient} =~ $w) {
$self->mylog_action($attr, 'pass', 'recipient whitelist');
return 'DUNNO';
}
}
# Check auto whitelist clients (see below for explanation)
my ($cawl_key, $cawl_count, $cawl_last, $cawl_entry);
if($self->{pgl}{awl_clients}) {
# lookup cawl
$cawl_key = $attr->{client_address};
if($self->{pgl}{privacy}) {
$cawl_key = Digest::SHA1::sha1_hex($cawl_key);
}
($cawl_count, $cawl_last, $cawl_entry) = $self->ldap_cawl_lookup($cawl_key);
# let through if count is enough
if(defined $cawl_count and $cawl_count >= $self->{pgl}{awl_clients})
{
if($now >= $cawl_last + $self->{pgl}{awl_window}) {
$cawl_count++; # for statistics
$self->ldap_cawl_update2($cawl_count, $now, $cawl_key, $cawl_entry);
}
$self->mylog_action($attr, 'pass', 'client AWL');
return 'DUNNO';
}
}
# lookup: prepare data
my $sender = lc($self->do_sender_substitutions($attr->{sender}));
my $recip = lc($attr->{recipient});
my ($client_net, $client_host) =
$self->do_client_substitutions($attr->{client_address}, $attr->{client_name});
if($self->{pgl}{privacy}) {
$sender = Digest::SHA1::sha1_hex($sender);
$recip = Digest::SHA1::sha1_hex($recip);
$client_net = Digest::SHA1::sha1_hex($client_net);
}
my ($first, $last, $trip_entry) = $self->ldap_triplet_lookup($client_net, $sender, $recip);
my $last_was_successful=0;
if(defined $first) {
my $Xdiff = $last-$first;
$self->mylog(2, "Back from ldap_triplet_lookup. I actually got back: $first, $last, which is: $Xdiff" );
# find out if the last time was unsuccessful, so that we can add a header
# to say how much had to be waited
if($last - $first >= $self->{pgl}{delay}) {
$last_was_successful=1;
}
else {
# discard stored first-seen if it is the first retrial and
# it is beyond the retry_window
$first = $now if $now-$first > $self->{pgl}{config}->param("retry-window");
}
}
else {
$self->mylog(2, " Back from ldap_triplet_lookup. Was empty. Greylisting.");
$first = $now;
}
# update
if(not defined $last) {
$self->ldap_triplet_create(
$client_net, $sender, $recip,
$client_host, $first, $now, $now-$first
);
}
else {
$self->ldap_triplet_update(
$client_host, $first, $now, $now-$first,
$client_net, $sender, $recip, $trip_entry
);
}
my $diff = $self->{pgl}{delay} - ($now - $first);
# auto whitelist clients
# algorithm:
# - on successful entry in the greylist db of a triplet:
# - client not whitelisted yet? -> increase count, whitelist if count > 10 or so
# - client whitelisted already? -> update last-seen timestamp
if($self->{pgl}{awl_clients}) {
# greylisting succeeded
if($diff <= 0 and !$last_was_successful) {
# enough time has passed (record only one attempt per window)
if(! defined $cawl_last or $now >= $cawl_last + $self->{pgl}{awl_window}) {
# ok, increase count
$cawl_count++;
# log if client has reached the count and is now whitelisted
my $cawl_first_t = undef;
if($cawl_count==$self->{pgl}{awl_clients}) {
my $client = $attr->{client_name} ?
$attr->{client_name}.'['.$attr->{client_address}.']' :
$attr->{client_address};
$self->mylog(1, "whitelisted: $client");
$cawl_first_t = $now;
}
# cawl database: insert or update
if($cawl_count==1) {
$self->ldap_cawl_create(
$cawl_key, $cawl_count, $cawl_first_t, $now
);
}
else {
$self->ldap_cawl_update(
$cawl_count, $now, $cawl_key, $cawl_first_t, $cawl_entry
);
}
}
}
}
# not enough waited? -> greylist
if ($diff > 0 ) {
my $msg = $self->{pgl}{greylist_text};
# Workaround for an Exchange bug related to Greylisting:
# use DSN 4.2.0 instead of the default 4.7.1. This works
# only with Postfix 2.3 though and we know that Postfix >= 2.3
# always defines the etrn_domain attribute (is this really true and
# guaranteed in future versions? I don't know...)
$msg = '4.2.0 ' . $msg if defined $attr->{etrn_domain} and
$msg !~ /^\d/;
$msg =~ s/\%s/$diff/g;
my $recip_domain = $attr->{recipient}; $recip_domain =~ s/.*\@//;
#lets make this greedy. Why not?
$msg =~ s/\%r/$recip_domain/g;
$self->mylog_action($attr, 'greylist',
$now != $first ? "early-retry (${diff}s missing)" : "new"
);
return "$self->{pgl}{greylist_action} $msg";
}
# X-Greylist header:
if(!$last_was_successful and $self->is_new_instance($attr->{instance})) {
my $Xdelay = $now - $first;
$self->log(1, "Passing; triplet found. Delay: $Xdelay");
# syslog
my $client = ($attr->{client_name} and $attr->{client_name} ne 'unknown') ?
$attr->{client_name} : $attr->{client_address};
# add X-Greylist header
my $date = strftime("%a, %d %b %Y %T %Z", localtime);
$self->mylog_action($attr, 'pass', 'triplet found', 'delay='.($now-$first));
return 'PREPEND X-Greylist: delayed '.($now-$first).
" seconds by postgrey-$VERSION at $self->{pgl}{hostname}; $date";
}
$self->mylog_action($attr, 'pass', 'triplet found');
return 'DUNNO';
}
sub dump_whitelists() {
my ($self) = @_;
print "Dumping Whitelists\n\twhitelist_recipients:\n";
print Dumper $self->{pgl}{whitelist_recipients};
print "\twhitelist_clients:\n";
print Dumper $self->{pgl}{whitelist_clients};
print "\twhitelist_ips:\n";
print Dumper $self->{pgl}{whitelist_ips};
print "\twhitelist_cidr:\n";
print Dumper $self->{pgl}{whitelist_cidr};
}
sub main()
{
# save arguments for Net:Server HUP restart
my @ARGV_saved = @ARGV;
# do not output any localized texts!
setlocale(LC_ALL, 'C');
# parse options
my %opt = ();
my $Config;
GetOptions(\%opt, 'help|h',
'man',
'version',
'noaction|no-action|n',
'config=s',
'dumpconfig',
'dumpwhitelist'
) or exit(1);
if($opt{help}) { pod2usage(1) }
if($opt{man}) { pod2usage(-exitstatus => 0, -verbose => 2) }
if($opt{version}) { print "postgreyldap $VERSION\n"; exit(0) }
if($opt{noaction}) { die "ERROR: don't know how to \"no-action\".\n" }
unless (defined ($opt{'config'})) {
print "ERROR: --config must be specified\n";
pod2usage(1);
}
# Load the config file
$Config = new Config::Simple();
$Config->read($opt{'config'}) ||
die ("Error reading config file: " . $Config->error());
$Config->param("server") || die ("No 'server' set in LDAP configuration\n");
$Config->param("dn") || die ("No 'dn' set in LDAP configuration\n");
$Config->param("version") || $Config->param("version", 3);
$Config->param("password") || die ("No 'password' set in LDAP configuration\n");
$Config->param("version") eq 3 || $Config->param("version") eq 2 ||
die ("LDAP version must be 2 or 3");
defined $Config->param("unix") or defined $Config->param("inet") or
die "ERROR: unix or inet must be specified\n";
# bind only localhost if no host is specified
if(defined $Config->param("inet") and $Config->param("inet")=~/^\d+$/) {
$Config->param("inet", "localhost:" . $Config->param("inet"));
}
# retry window
my $retry_window = 24*3600*2; # default: 2 days
if(defined $Config->param("retry-window")) {
my $x = $Config->param("retry-window");
if($x =~ /^(\d+)h$/i) {
$Config->param("retry-window", $1 * 3600);
}
elsif($x =~ /^(\d+)d?$/) {
$Config->param("retry-window", $1 * 24 * 3600);
}
else {
die "ERROR: retry-window must be either a number of days or a number\n",
" followed by 'h' for hours ('6h' for example).\n",
" Was: " . $Config->param("retry-window");
}
}
unless ($Config->param("lockdir")) {
$Config->param("lockdir", $DEFAULT_LOCKDIR);
}
# determine proper "logsock" for Sys::Syslog
my $syslog_logsock;
if(defined $Sys::Syslog::VERSION and $Sys::Syslog::VERSION ge '0.15'
and defined $Net::Server::VERSION and $Net::Server::VERSION ge '0.97') {
# use 'native' when Sys::Syslog >= 0.15
$syslog_logsock = 'native';
} elsif($^O eq 'solaris') {
# 'stream' is broken and 'unix' doesn't work on Solaris: only 'inet'
# seems to be useable with Sys::Syslog < 0.15
$syslog_logsock = 'inet';
} else {
$syslog_logsock = 'unix';
}
#Cleanup our configuration settings. In most cases, we will silently
#ignore errors, and set to the default.
#
#This is possibly slightly evil, but we do give the option of dumping
#the config, as we will actually use it.
# Workaround: Net::Server doesn't allow for a value of 'listen' higher than 999
if(defined $Config->param("listen-queue-size") and $Config->param("listen-queue-size") > 999) {
$Config->param("listen-queue-size", 999);
}
if(defined $Config->param("daemonize") && $Config->param("daemonize") =~ /(false|no)/i ) {
$Config->param("daemonize", 0);
} else {
$Config->param("daemonize", 1);
}
if(defined $Config->param("privacy") && $Config->param("privacy") =~ /(true|yes)/i ) {
$Config->param("privacy", 1);
# --privacy requires Digest::SHA1
require Digest::SHA1;
} else {
$Config->param("privacy", 0);
}
unless ($Config->param("log-level") =~ /^(\d)$/) {
$Config->param("log-level", 1);
}
unless (defined $Config->param("lookup-by") && $Config->param("lookup-by") =~ /^subnet$/i) {