forked from max197616/zapret
/
zapret.pl
executable file
·1242 lines (1083 loc) · 31.9 KB
/
zapret.pl
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 -w
use strict;
use warnings;
use SOAP::Lite;
use DBI;
use Data::Dumper;
use MIME::Base64;
use utf8;
use XML::Simple;
use URI 1.69;
use NetAddr::IP;
use Digest::MD5 qw(md5_hex);
use Encode qw(encode_utf8);
use Net::SMTP;
use POSIX;
use POSIX qw(strftime);
use Config::Simple;
use File::Basename;
use Net::IP qw(:PROC);
use AnyEvent;
use AnyEvent::DNS;
use Log::Log4perl;
use Getopt::Long;
use URI::UTF8::Punycode;
binmode(STDOUT,':utf8');
binmode(STDERR,':utf8');
######## Config #########
my $openssl_bin_path="/usr/local/gost-ssl/bin";
my $dir = File::Basename::dirname($0);
my $Config = {};
my $config_file=$dir.'/zapret.conf';
my $force_load='';
my $log_file=$dir."/zapret_log.conf";
GetOptions("force_load" => \$force_load,
"log=s" => \$log_file,
"config=s" => \$config_file) or die "Error no command line arguments\n";
Config::Simple->import_from($config_file, $Config) or die "Can't open ".$config_file." for reading!\n";
Log::Log4perl::init( $log_file );
my $logger=Log::Log4perl->get_logger();
my $api_url = $Config->{'API.url'} || die "API.url not defined.";
my $req_file = $Config->{'PATH.req_file'} || die "PATH.req_file not defined.";
$req_file = $dir."/".$req_file;
my $sig_file = $Config->{'PATH.sig_file'} || die "PATH.sig_file not defined.";
$sig_file = $dir."/".$sig_file;
my $template_file = $Config->{'PATH.template_file'} || die "PATH.template_file not defined.";
$template_file = $dir."/".$template_file;
my $db_host = $Config->{'DB.host'} || die "DB.host not defined.";
my $db_user = $Config->{'DB.user'} || die "DB.user not defined.";
my $db_pass = $Config->{'DB.password'} || die "DB.password not defined.";
my $db_name = $Config->{'DB.name'} || die "DB.name not defined.";
my $resolve = $Config->{'NS.resolve'} || 0;
my @resolvers = $Config->{'NS.resolvers'} || ();
my @resolvers_new;
foreach my $n (@{$resolvers[0]})
{
push(@resolvers_new,AnyEvent::Socket::parse_address($n));
}
my $ipv6_nslookup = $Config->{'NS.ipv6_support'} || 0;
if(lc($ipv6_nslookup) eq "true" || lc($ipv6_nslookup) eq "yes")
{
$ipv6_nslookup=1;
} else {
$ipv6_nslookup=0;
}
my $keep_resolved = $Config->{'NS.keep_resolved'} || 0;
if(lc($keep_resolved) eq "yes" || lc($keep_resolved) eq "true")
{
$keep_resolved=1;
} else {
$keep_resolved=0;
}
my $dns_timeout = $Config->{'NS.timeout'} || 1;
$dns_timeout = int($dns_timeout) if($dns_timeout);
my $mail_send = $Config->{'MAIL.send'} || 0;
my @mail_to = $Config->{'MAIL.to'} || die "MAIL.to not defined.";
my $smtp_auth = $Config->{'MAIL.auth'} || 0;
my $smtp_from = $Config->{'MAIL.from'} || die "MAIL.from not defined.";
my $smtp_host = $Config->{'MAIL.server'} || die "MAIL.server not defined.";
my $smtp_port = $Config->{'MAIL.port'} || die "MAIL.port not defined.";
my $smtp_login = $Config->{'MAIL.login'} || "";
my $smtp_password = $Config->{'MAIL.password'} || "";
my $mail_excludes = $Config->{'MAIL.excludes'} || 0;
my $mail_new = $Config->{'MAIL.new'} || 0;
my $mail_new_ips = $Config->{'MAIL.new_ips'} || 0;
my $mail_removed = $Config->{'MAIL.removed'} || 0;
my $mail_removed_ips = $Config->{'MAIL.removed_ips'} || 0;
my $mail_alone = $Config->{'MAIL.alone'} || 0;
my $form_request = $Config->{'API.form_request'} || 0;
my $ldd_iterations = 0;
######## End config #####
my $DBH;
my ($lastDumpDateOld, $lastAction, $lastCode, $lastResult);
dbConnect();
getParams();
my %NEW = ();
my %OLD = ();
my %OLD_IPS = ();
my %OLD_ONLY_IPS = ();
my %OLD_DOMAINS = ();
my %OLD_URLS = ();
my %OLD_SUBNETS = ();
my %OLD_TRUE = ();
my %OLD_TRUE_IPS = ();
my %OLD_TRUE_ONLY_IPS = ();
my %OLD_TRUE_DOMAINS = ();
my %OLD_TRUE_URLS = ();
my %OLD_TRUE_SUBNETS = ();
my %EX_IPS = ();
my %EX_DOMAINS = ();
my %EX_SUBNETS = ();
my %resolver_cache;
my $MAILTEXT = '';
my $MAIL_ADDED = '';
my $MAIL_ADDED_IPS = '';
my $MAIL_REMOVED = '';
my $MAIL_REMOVED_IPS = '';
my $MAIL_EXCLUDES = '';
my $MAIL_ALONE = '';
my $resolved_domains=0;
my $deleted_old_domains=0;
my $deleted_old_urls=0;
my $deleted_old_ips=0;
my $deleted_old_only_ips=0;
my $deleted_old_subnets=0;
my $deleted_old_records=0;
my $added_ipv4_ips=0;
my $added_ipv6_ips=0;
my $added_domains=0;
my $added_urls=0;
my $added_subnets=0;
my $added_records=0;
$logger->debug("Last dump date:\t".$lastDumpDateOld);
$logger->debug("Last action:\t".$lastAction);
$logger->debug("Last code:\t".$lastCode);
$logger->debug("Last result:\t".$lastResult);
#############################################################
my $start_time=localtime();
$logger->info("Starting RKN at ".$start_time);
if( $lastResult eq 'send' )
{
$logger->info("Last request is send, waiting for the data...");
while (getResult())
{
$logger->info("Reestr not yet ready. Waiting...");
sleep(5);
}
exit 0;
}
if(checkDumpDate())
{
sendRequest();
while (getResult())
{
$logger->info("Reestr not yet ready. Waiting...");
sleep(5);
}
}
exit 0;
sub getResult
{
$logger->debug("Getting result...");
my $soap = SOAP::Lite->service( $api_url );
my @result;
eval
{
@result = $soap->getResult( $lastCode );
};
if( $@ )
{
$logger->fatal("Error while getResult(): ".$@);
exit;
}
if( !@result )
{
$logger->fatal("Result not defined!");
$logger->error( Dumper( @result ));
exit;
}
if( !($result[0] eq 'true' ) )
{
# Some error
my $comment = $result[1];
$logger->error("Can not get result: ".$comment);
# This is utf-8:
if( $result[2] == 0 )
{
return 1;
} else {
set('lastResult', 'err');
set('lastAction', 'getResult');
exit;
}
} else {
unlink $dir.'/dump.xml';
unlink $dir.'/arch.zip';
unlink $dir.'/dump.xml.sig';
my $zip = decode_base64($result[1]);
open F, '>'.$dir.'/arch.zip' || die "Can't open arch.zip for writing!\n".$! ;
binmode F;
print F $zip;
close F;
`unzip -o $dir/arch.zip -d $dir/`;
$logger->debug("Got result, parsing dump.");
set('lasltAction', 'getResult');
set('lastResult', 'got');
set('lastDumpDate', time);
parseDump();
# статистика
$logger->info("Load iterations: ".$ldd_iterations.", resolved domains: ".$resolved_domains);
$logger->info("Added: domains: ".$added_domains.", urls: ".$added_urls.", IPv4 ips: ".$added_ipv4_ips.", IPv6 ips: ".$added_ipv6_ips.", subnets: ".$added_subnets.", records: ".$added_records);
$logger->info("Deleted: old domains: ".$deleted_old_domains.", old urls: ".$deleted_old_urls.", old ips: ".$deleted_old_ips.", old only ips: ".$deleted_old_only_ips.", old subnets: ".$deleted_old_subnets.", old records: ".$deleted_old_records);
my $stop_time=localtime();
$logger->info("Stopping RKN at ".$stop_time);
}
return 0;
}
sub checkDumpDate
{
$logger->debug("Checking dump date...");
my $lastDumpDate = getLastDumpDate();
$logger->debug("RKN last dump date: ".$lastDumpDate);
if( $lastDumpDateOld eq '' || $lastDumpDate > $lastDumpDateOld || $force_load)
{
$logger->debug("lastDumpDate > prev. dump date. Working now.");
return 1;
}
$logger->info("lastDumpDate <= prev. dump date. Exiting.");
return 0;
}
sub getLastDumpDate
{
$ldd_iterations++;
my @result;
eval {
my $soap= SOAP::Lite->service( $api_url );
@result = $soap->getLastDumpDateEx();
};
if( $@ ) {
$logger->error("Error while getLastDumpDate: ".$@);
if( $ldd_iterations < 4 ) {
$logger->info("Retrying...");
return getLastDumpDate();
} else {
$logger->fatal("3 attempts failed, giving up");
exit;
}
}
if( !@result ) {
$logger->error("Soap result not defined, retrying...");
if( $ldd_iterations < 4 ) {
return getLastDumpDate();
} else {
$logger->fatal("3 attempts failed, giving up.");
exit;
}
}
if( !defined($result[0]) || $result[0] !~ /^(\d+)$/ ) {
$logger->error("Can't get lastDumpDateEx!");
$logger->error(print Dumper(@result));
if( $ldd_iterations < 4 ) {
$logger->info("Retrying...");
return getLastDumpDate();
} else {
$logger->fatal("3 attempts failed, giving up.");
exit;
}
} else {
my $stamp = $result[0] / 1000;
return $stamp;
}
}
sub formRequest
{
my $now = time();
my $tz = strftime("%z", localtime($now));
$tz =~ s/(\d{2})(\d{2})/$1:$2/;
my $dt = strftime("%Y-%m-%dT%H:%M:%S", localtime($now)) . $tz;
my $buf = '';
my $new = '';
open TMPL, "<", $template_file or die "Can't open ".$template_file." for reading!\n";
while( <TMPL> ) {
my $line = $_;
$line =~ s/{{TIME}}/$dt/g;
$new .= $line;
}
close TMPL;
open REQ, ">", $req_file;
print REQ $new;
close REQ;
`$openssl_bin_path/openssl smime -sign -in $req_file -out $sig_file -binary -signer $dir/cert.pem -outform DER`;
}
sub sendRequest
{
$logger->debug( "Sending request...");
if( $form_request == 1 )
{
formRequest();
}
my ( $req, $sig, $buf );
# request
open F, '<'.$req_file || die $!;
binmode F;
while( (read F, $buf, 65536) != 0 ) {
$req .= $buf;
}
close F;
# signature
open F, '<'.$sig_file || die $!;
binmode F;
while( (read F, $buf, 65536) != 0 ) {
$sig .= $buf;
}
close F;
my $soap = SOAP::Lite->service( $api_url );
my @result = $soap->sendRequest(
$req,
$sig,
"2.1"
);
my $res = $result[0];
if( $res eq 'true' ) {
# Everyhing OK
my $code = $result[2];
$logger->debug( $result[1] );
set('lastCode', $code);
set('lastAction', 'sendRequest');
set('lastActionDate', time );
set('lastResult', 'send');
return 1;
} else {
# Something goes wrong
my $code = $result[1];
$logger->debug("ERROR while sending request: ".$code);
set('lastResult', 'err');
die;
}
}
sub dbConnect {
$DBH = DBI->connect_cached("DBI:mysql:database=".$db_name.";host=".$db_host, $db_user, $db_pass,{mysql_enable_utf8 => 1}) or die DBI->errstr;
$DBH->do("set names utf8");
}
sub set {
my $param = shift;
my $value = shift;
my $sth = $DBH->prepare("UPDATE zap2_settings SET value = ? WHERE param = ?");
$sth->bind_param(1, $value);
$sth->bind_param(2, $param);
$sth->execute or die DBI->errstr;
}
sub getParams {
my $sth = $DBH->prepare("SELECT param,value FROM zap2_settings");
$sth->execute or die DBI->errstr;
while( my $ref = $sth->fetchrow_arrayref ) {
if( $$ref[0] eq 'lastDumpDate' )
{
$lastDumpDateOld = $$ref[1];
}
if( $$ref[0] eq 'lastAction' )
{
$lastAction = $$ref[1];
}
if( $$ref[0] eq 'lastCode' )
{
$lastCode = $$ref[1];
}
if( $$ref[0] eq 'lastResult' )
{
$lastResult = $$ref[1];
}
}
}
sub parseDump
{
$logger->debug("Parsing dump...");
my $xml = new XML::Simple;
my $data = $xml->XMLin($dir.'/dump.xml');
foreach my $k (keys %{$data->{content}})
{
eval {
my ( $decision_number, $decision_org, $decision_date, $entry_type, $include_time );
$decision_number = $decision_org = $decision_date = $entry_type = '';
my $decision_id = $k;
$entry_type = '';
my $content = $data->{content}->{$k};
$decision_number = $content->{decision}->{number} if defined( $content->{decision}->{number} );
$decision_org = $content->{decision}->{org} if defined( $content->{decision}->{org} );
$decision_date = $content->{decision}->{date} if defined( $content->{decision}->{org} );
$entry_type = $content->{entryType} if defined( $content->{entryType} );
$include_time = $content->{includeTime} if defined( $content->{includeTime} );
my %item = (
'entry_type' => $entry_type,
'decision_num' => $decision_number,
'decision_id' => $decision_id,
'decision_date' => $decision_date,
'decision_org' => $decision_org,
'include_time' => $include_time
);
my @domains = ();
my @urls = ();
my @ips = ();
my @subnets = ();
my $blockType=defined($content->{blockType}) ? $content->{blockType} : "default";
if($blockType ne "domain" && $blockType ne "default")
{
$logger->error("Not recognized blockType: $blockType");
}
#пишем домены, если только стоит тип блокировки по домену
# Domains
# if($blockType eq "domain")
# {
if( defined( $content->{domain} ) )
{
if(ref($content->{domain}) eq 'ARRAY')
{
foreach( @{$content->{domain}} )
{
push @domains, $_;
}
} else {
push @domains, $content->{domain};
}
}
$item{'domains'} = \@domains;
# }
# URLs
if( defined( $content->{url} ) )
{
if( ref($content->{url}) eq 'ARRAY' )
{
foreach( @{$content->{url}} )
{
push @urls, $_;
}
} else {
push @urls, $content->{url};
}
}
$item{'urls'} = \@urls;
# IPs
if( defined( $content->{ip} ) )
{
if( ref($content->{ip}) eq 'ARRAY' )
{
foreach( @{$content->{ip}} )
{
push @ips, $_;
}
} else {
push @ips, $content->{ip};
}
}
$item{'ips'} = \@ips;
# Subnets
if( defined( $content->{ipSubnet} ) )
{
if( ref($content->{ipSubnet}) eq 'ARRAY' )
{
foreach( @{$content->{ipSubnet}} )
{
push @subnets, $_;
}
} else {
push @subnets, $content->{ipSubnet};
}
}
$item{'subnets'} = \@subnets;
# $logger->debug( " -- Decision (id ".$decision_id."): ".$decision_number.", from ".$decision_date.", org: ".$decision_org." \n" );
$NEW{$decision_id} = \%item;
};
$logger->error("Eval! ".$@) if $@;
}
# Dump parsed.
# Get old data from DB
getOld();
my $resolver = AnyEvent::DNS->new(timeout => [$dns_timeout], max_outstanding => 50, server => \@resolvers_new); # создаём резолвер с нужными параметрами
my $cv = AnyEvent->condvar;
processNew($resolver,$cv);
if($resolve == 1)
{
$logger->debug("Wait while all resolvers finished");
$cv->recv;
}
clearOld();
processMail();
set('lastAction', 'getResult');
set('lastResult', 'got');
set('lastDumpDate', time() );
};
# Cleanup old entries
sub clearOld {
foreach my $domain ( keys %OLD_TRUE_DOMAINS ) {
delDomain( $OLD_TRUE_DOMAINS{$domain}[0], $OLD_TRUE_DOMAINS{$domain}[1] );
$deleted_old_domains++;
# $logger->debug("Deleting domain id ".$OLD_TRUE_DOMAINS{$domain}[0]." ( ".$OLD_TRUE_DOMAINS{$domain}[1]." )");
}
foreach my $url ( keys %OLD_TRUE_URLS ) {
$deleted_old_urls++;
delUrl( $OLD_TRUE_URLS{$url}[0], $OLD_TRUE_URLS{$url}[1] );
# $logger->debug("Deleting url id ".$OLD_TRUE_URLS{$url}[0]." (".$OLD_TRUE_URLS{$url}[1].")");
}
foreach my $ip ( keys %OLD_TRUE_IPS )
{
$deleted_old_ips++;
delIp( $OLD_TRUE_IPS{$ip}[0], $OLD_TRUE_IPS{$ip}[1] );
}
foreach my $ip ( keys %OLD_TRUE_ONLY_IPS ) {
$deleted_old_only_ips++;
delIpOnly( $OLD_TRUE_ONLY_IPS{$ip}[0], $OLD_TRUE_ONLY_IPS{$ip}[1] );
}
foreach my $net ( keys %OLD_TRUE_SUBNETS ) {
$deleted_old_subnets++;
delSubnet( $OLD_TRUE_SUBNETS{$net}[0], $OLD_TRUE_SUBNETS{$net}[1] );
}
foreach my $item ( keys %OLD_TRUE ) {
$deleted_old_records++;
#print $OLD_TRUE{$item}->{id};
# $logger->debug("Deleting decision record of id ".$OLD_TRUE{$item}->{id});
delRecord($OLD_TRUE{$item}->{id});
}
};
sub processNew {
my $resolver = shift;
my $cv = shift;
my $sth;
eval {
# Content items:
foreach my $d_id ( keys %NEW ) {
my $record_id = 0;
if( !defined( $OLD{$d_id} ) )
{
# New record
$sth = $DBH->prepare("INSERT INTO zap2_records(decision_id,decision_date,decision_num,decision_org,include_time,entry_type) VALUES(?,?,?,?,?,?)");
$sth->bind_param(1, $d_id );
$sth->bind_param(2, $NEW{$d_id}->{decision_date} );
$sth->bind_param(3, $NEW{$d_id}->{decision_num} );
$sth->bind_param(4, $NEW{$d_id}->{decision_org} );
$sth->bind_param(5, $NEW{$d_id}->{include_time} );
$sth->bind_param(6, $NEW{$d_id}->{entry_type} );
$sth->execute;
$record_id = $sth->{mysql_insertid};
$OLD{$d_id} = $record_id;
$MAIL_ADDED .= "Added new content: id ".$record_id."\n";
$logger->debug("Added new content: id ".$record_id);
$added_records++;
} else {
delete $OLD_TRUE{$d_id};
$record_id = $OLD{$d_id}->{id};
}
# URLs
my $processed_urls=0;
if( ref($NEW{$d_id}->{urls}) eq 'ARRAY' )
{
foreach my $url ( @{$NEW{$d_id}->{urls}} )
{
$processed_urls++;
# Check for ex. domain
my $uri = URI->new($url);
my $scheme = $uri->scheme();
if($scheme ne "http" && $scheme ne "https")
{
$logger->error("Unsupported scheme in url: $url for resolving.");
} else {
my $url_domain = $uri->host();
#my @res = ( $url =~ m!^(?:http://|https://)?([^(/|\?)]+)!i );
#my $url_domain = $res[0];
if( defined( $EX_DOMAINS{$url_domain} ) ) {
# binmode(STDOUT, ':utf8');
# print "EXCLUDE DOMAIN ".$url_domain." (URL ".$url.")\n";
$MAIL_EXCLUDES .= "Excluding URL (caused by excluded domain ".$url_domain."): ".$url."\n";
next;
}
Resolve( $url_domain, $record_id, $resolver, $cv);
}
if( !defined( $OLD_URLS{md5_hex(encode_utf8($url))} ) ) {
# binmode(STDOUT, ':utf8');
# print "New URL: ".encode_utf8($url)."\n";
# print "MD5 hex: ".md5_hex(encode_utf8($url))."\n";
$sth = $DBH->prepare("INSERT INTO zap2_urls(record_id, url) VALUES(?,?)");
$sth->bind_param(1, $record_id);
$sth->bind_param(2, $url);
$sth->execute;
$OLD_URLS{md5_hex(encode_utf8($url))} = 1;
$MAIL_ADDED .= "Added new URL: ".$url."\n";
$logger->debug("Added new URL: ".$url);
$added_urls++;
} else {
# delete from old_true_urls
delete $OLD_TRUE_URLS{md5_hex(encode_utf8($url))};
}
}
}
my $need_to_block_domain=0;
if(!$processed_urls)
{
$logger->debug("Item $d_id hasn't defined URL, must block by DOMAIN");
$need_to_block_domain=1;
}
my $processed_domains=0;
# Domain items:
if( ref($NEW{$d_id}->{domains}) eq 'ARRAY' && $need_to_block_domain)
{
foreach my $domain( @{$NEW{$d_id}->{domains}} )
{
# Check for excludes
if( defined( $EX_DOMAINS{$domain} ) ) {
# print "EXCLUDE DOMAIN: ".$domain."\n";
$MAIL_EXCLUDES .= "Excluding domain: ".$domain."\n";
$logger->debug("Excluding domain: ".$domain);
next;
}
$processed_domains++;
Resolve( $domain, $record_id, $resolver, $cv );
if( !defined( $OLD_DOMAINS{md5_hex(encode_utf8($domain))} ) )
{
# print "New domain: ".$domain."\n";
$sth = $DBH->prepare("INSERT INTO zap2_domains(record_id, domain) VALUES(?,?)");
$sth->bind_param(1, $record_id);
$sth->bind_param(2, $domain);
$sth->execute;
$OLD_DOMAINS{md5_hex(encode_utf8($domain))} = 1;
$MAIL_ADDED .= "Added new domain: ".$domain."\n";
$logger->debug("Added new domain: ".$domain);
$added_domains++;
} else {
delete $OLD_TRUE_DOMAINS{md5_hex(encode_utf8($domain))};
}
}
}
my $need_to_block_ip=0;
if(!$processed_urls && !$processed_domains)
{
$logger->debug("Item $d_id hasn't url and domain, need to block by IP");
$need_to_block_ip=1;
}
# IPS
if( ref($NEW{$d_id}->{ips}) eq 'ARRAY' )
{
foreach my $ip ( @{$NEW{$d_id}->{ips}} )
{
if($need_to_block_ip)
{
if( !defined( $OLD_ONLY_IPS{$ip} ) )
{
my $ipa = new Net::IP($ip);
my $ip_packed=pack("B*",$ipa->binip());
$sth = $DBH->prepare("INSERT INTO zap2_only_ips(record_id, ip, resolved) VALUES(?,?,0)");
$sth->bind_param(1, $record_id);
$sth->bind_param(2, $ip_packed);
$sth->execute;
$OLD_ONLY_IPS{$ipa->ip()} = 1;
$MAIL_ADDED_IPS .= "Added new ONLY IP: ".$ipa->ip()."\n";
$logger->debug("New ONLY ip: ".$ipa->ip());
} else {
delete $OLD_ONLY_IPS{$ip};
}
next;
}
my $exclude = 0;
# Check excluded nets
for my $subnet (keys %EX_SUBNETS) {
my $ipadr = NetAddr::IP->new( $ip );
my $net = NetAddr::IP->new( $subnet );
if( $ipadr && $net ) {
if( $ipadr->within($net) ) {
# print "Excluding ip ".$ip.": overlaps with excluded subnet ".$subnet."\n";
$MAIL_EXCLUDES .= "Excluding ip ".$ip.": overlaps with excluded subnet ".$subnet."\n";
$logger->debug("Excluding ip ".$ip);
$exclude = 1;
last;
}
}
}
next if( $exclude == 1 );
# Check for ex. ip
if( defined($EX_IPS{$ip}) )
{
# print "Excluding ip ".$ip.": match excluded ip in DB.\n";
$MAIL_EXCLUDES .= "Excluding ip ".$ip.": match excluded ip in DB.\n";
$logger->debug("Excluding ip ".$ip);
next;
}
if( !defined( $OLD_IPS{$ip} ) )
{
# print "New ip: ".$ip."\n";
my $ipa = new Net::IP($ip);
my $ip_packed=pack("B*",$ipa->binip());
$sth = $DBH->prepare("INSERT INTO zap2_ips(record_id, ip, resolved) VALUES(?,?,0)");
$sth->bind_param(1, $record_id);
$sth->bind_param(2, $ip_packed);
$sth->execute;
$OLD_IPS{$ipa->ip()} = 1;
$MAIL_ADDED_IPS .= "Added new IP: ".$ipa->ip()."\n";
$logger->debug("New ip: ".$ipa->ip());
if($ipa->version() == 4)
{
$added_ipv4_ips++;
} else {
$added_ipv6_ips++;
}
} else {
delete $OLD_TRUE_IPS{$ip};
}
}
}
# Subnets
if( ref($NEW{$d_id}->{subnets}) eq 'ARRAY' )
{
foreach my $subnet ( @{$NEW{$d_id}->{subnets}} )
{
my $exclude = 0;
# Check for excludes. Ips:
for my $ip (keys %EX_IPS)
{
# print $ip."\n";
my $ipadr = NetAddr::IP->new( $ip );
my $net = NetAddr::IP->new( $subnet );
if( $ipadr && $net ) {
if( $ipadr->within($net) ) {
# print "Exclude subnet ".$subnet.": contains excluded IP ".$ip."\n";
$MAIL_EXCLUDES .= "Excluding subnet ".$subnet.": contains excluded ip ".$ip."\n";
$logger->debug("Excluding subnet ".$subnet);
$exclude = 1;
}
}
}
# And nets:
for my $net (keys %EX_SUBNETS)
{
my $net1 = NetAddr::IP->new( $net );
my $net2 = NetAddr::IP->new( $net );
if( $net1 && $net2 ) {
if( $net1->within( $net2 ) || $net2->within( $net1 ) ) {
# print "Exclude subnet ".$subnet.": overlaps with excluded net ".$net."\n";
$MAIL_EXCLUDES .= "Excluding subnet ".$subnet.": overlaps with excluded net ".$net."\n";
$exclude = 1;
$logger->debug("Excluding subnet ".$subnet);
last;
}
}
}
if( $exclude == 1 ) {
next;
}
if( !defined( $OLD_SUBNETS{$subnet} ) )
{
# print "New subnet: ".$subnet."\n";
$sth = $DBH->prepare("INSERT INTO zap2_subnets(record_id, subnet) VALUES(?,?)");
$sth->bind_param(1, $record_id);
$sth->bind_param(2, $subnet);
$sth->execute;
$OLD_SUBNETS{$subnet} = 1;
$MAIL_ADDED .= "Added new subnet: ".$subnet."\n";
$logger->debug("Added new subnet: ".$subnet);
# Check, if there no any othere parameters in this content
if(
( !defined($NEW{$d_id}->{domains}) || ref($NEW{$d_id}->{domains}) ne 'ARRAY' || scalar(@{$NEW{$d_id}->{domains}}) == 0 )
&&
( !defined($NEW{$d_id}->{urls}) || ref($NEW{$d_id}->{urls}) ne 'ARRAY' || scalar(@{$NEW{$d_id}->{urls}}) == 0 )
) {
$MAIL_ALONE .= "Alert! Subnet ".$subnet." added without any domain/url!\n";
}
$added_subnets++;
} else {
delete $OLD_TRUE_SUBNETS{$subnet};
}
}
}
}
};
$logger->error("Eval: ".$@) if $@;
};
sub getOld {
%OLD = ();
%OLD_IPS = ();
%OLD_ONLY_IPS = ();
%OLD_DOMAINS = ();
%OLD_SUBNETS = ();
%OLD_URLS = ();
%OLD_TRUE = ();
%OLD_TRUE_IPS = ();
%OLD_TRUE_ONLY_IPS = ();
%OLD_TRUE_DOMAINS = ();
%OLD_TRUE_SUBNETS = ();
%OLD_TRUE_URLS = ();
# Contents
my $sth = $DBH->prepare("SELECT id,date_add,decision_id,decision_date,decision_num,decision_org,include_time FROM zap2_records ORDER BY date_add");
$sth->execute or die DBI->errstr;
while( my $ref = $sth->fetchrow_arrayref ) {
my %item = (
'id' => $$ref[0],
'date_add' => $$ref[1],
'decision_id' => $$ref[2],
'decision_date' => $$ref[3],
'decision_num' => $$ref[4],
'decision_org' => $$ref[5],
'include_time' => $$ref[6]
);
$OLD{$$ref[2]} = \%item;
$OLD_TRUE{$$ref[2]} = \%item;
}
# Domains
$sth = $DBH->prepare("SELECT record_id, domain, id FROM zap2_domains ORDER BY date_add");
$sth->execute or die DBI->errstr;
while( my $ref = $sth->fetchrow_arrayref ) {
$OLD_DOMAINS{md5_hex(encode_utf8($$ref[1]))} = $$ref[0];
@{$OLD_TRUE_DOMAINS{md5_hex(encode_utf8($$ref[1]))}} = ( $$ref[2], $$ref[1], $$ref[0] );
}
# URLs
$sth = $DBH->prepare("SELECT id,record_id,url FROM zap2_urls ORDER BY date_add");
$sth->execute or die DBI->errstr;
while( my $ref = $sth->fetchrow_arrayref ) {
$OLD_URLS{md5_hex(encode_utf8($$ref[2]))} = $$ref[0];
@{$OLD_TRUE_URLS{md5_hex(encode_utf8($$ref[2]))}} = ( $$ref[0], $$ref[2], $$ref[1] );
}
# Subnets
$sth = $DBH->prepare("SELECT record_id, subnet, id FROM zap2_subnets ORDER BY date_add");
$sth->execute or die DBI->errstr;
while( my $ref = $sth->fetchrow_arrayref ) {
$OLD_SUBNETS{$$ref[1]} = $$ref[0];
@{$OLD_TRUE_SUBNETS{$$ref[1]}} = ( $$ref[2], $$ref[1] );
}
# Ips
$sth = $DBH->prepare("SELECT ip, record_id, id, resolved FROM zap2_ips ORDER BY date_add");
$sth->execute or die DBI->errstr;
while( my $ref = $sth->fetchrow_arrayref )
{
my $old_ip=get_ip($$ref[0]);
$OLD_IPS{$old_ip} = $$ref[1];
next if($keep_resolved == 1 && $$ref[3] eq "1"); # skeep to delete resolved ips
@{$OLD_TRUE_IPS{$old_ip}} = ( $$ref[2], $old_ip );
}
# ONLY ips
$sth = $DBH->prepare("SELECT ip, record_id, id FROM zap2_only_ips ORDER BY date_add");
# todo добавить поддержку ipv6
$sth->execute or die DBI->errstr;
while( my $ref = $sth->fetchrow_arrayref )
{
my $old_ip=get_ip($$ref[0]);
$OLD_ONLY_IPS{$old_ip} = $$ref[1];
@{$OLD_TRUE_ONLY_IPS{$old_ip}} = ( $$ref[2], $old_ip );
}
# Excludes
$sth = $DBH->prepare("SELECT subnet FROM zap2_ex_nets");
$sth->execute or die DBI->errstr;
while( my $ref = $sth->fetchrow_arrayref ) {
$EX_SUBNETS{$$ref[0]} = 1;
}
$sth = $DBH->prepare("SELECT inet_ntoa(ip) FROM zap2_ex_ips");
$sth->execute or die DBI->errstr;
while( my $ref = $sth->fetchrow_arrayref ) {
$EX_IPS{$$ref[0]} = 1;
}
$sth = $DBH->prepare("SELECT domain FROM zap2_ex_domains");
$sth->execute or die DBI->errstr;
while( my $ref = $sth->fetchrow_arrayref ) {
$EX_DOMAINS{$$ref[0]} = 1;
}
};
sub Resolve
{
my $domain = shift;
my $record_id = shift;
my $resolvera = shift || undef;
my $cv=shift || undef;
if( $resolve != 1 ) {
return;
}
if(defined $resolver_cache{md5_hex(encode_utf8($domain))})
{
$logger->debug("Domain $domain already resolved");
return;
}
my $type="a";
$type="*" if($ipv6_nslookup);
$resolver_cache{md5_hex(encode_utf8($domain))}=1;
resolve_async($cv,$domain,$resolvera,$type,$record_id);
}