clamavdownloader.pl 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #!/usr/bin/env perl
  2. #
  3. # File name: clamdownloader.pl
  4. # Author: Frederic Vanden Poel
  5. # Enhanced: Added UA, mirror fallback and CDIFF missing-history cache
  6. #
  7. #############################################################################
  8. use strict;
  9. use warnings;
  10. use Getopt::Long;
  11. use Net::DNS;
  12. use LWP::UserAgent;
  13. use HTTP::Request;
  14. use File::Copy;
  15. use File::Compare;
  16. # Base directory where ClamAV databases are stored
  17. my $clamdb = "/var/www/html/clamav";
  18. # Flag to skip daily.cvd update
  19. my $skip_daily = 0;
  20. # Parse command-line options
  21. GetOptions(
  22. 'skip-daily' => \$skip_daily,
  23. ) or die("Error in command-line arguments\n");
  24. # User-Agent string used for HTTP requests
  25. my $user_agent = 'ClamAV/1.4.3 (OS: Linux, ARCH: x86_64, CPU: x86_64, UUID: 98425604-444c-40ae-969a-df296bfa1581)';
  26. # Mirrors that provide full .cvd files (public, no 403)
  27. my @cvd_mirrors = (
  28. "https://database.clamav.net",
  29. "https://mirror.truenetwork.ru/clamav",
  30. );
  31. # Mirrors used for incremental .cdiff files
  32. my @cdiff_mirrors = (
  33. "https://database.clamav.net",
  34. "https://mirror.truenetwork.ru/clamav",
  35. );
  36. # Cache of CDIFF files known to be unavailable
  37. my %cdiff_history = ();
  38. load_cdiff_history();
  39. # Fetch TXT record containing current database versions
  40. my $txt = getTXT("current.cvd.clamav.net");
  41. exit unless $txt;
  42. # Switch to ClamAV database directory
  43. chdir($clamdb) || die ("Can't chdir to $clamdb : $!\n");
  44. print "TXT from DNS: $txt\n";
  45. # Save DNS TXT record locally for reference/debugging
  46. open my $dns_fh, '>', 'dns.txt' or die "Can't open dns.txt: $!";
  47. print $dns_fh "$txt";
  48. close $dns_fh;
  49. # Temporary directory for downloads
  50. mkdir("$clamdb/temp") unless -d "$clamdb/temp";
  51. # Parse fields from DNS TXT record
  52. my ( $clamv, $mainv, $dailyv, $x, $y, $z, $safebrowsingv, $bytecodev ) = split /:/, $txt;
  53. print "FIELDS main=$mainv daily=$dailyv bytecode=$bytecodev\n";
  54. # Update main database
  55. updateFile('main', $mainv);
  56. # Update daily database unless explicitly skipped
  57. unless ($skip_daily) {
  58. updateFile('daily', $dailyv);
  59. updateFileCdiff('daily', $dailyv);
  60. }
  61. # Update bytecode database
  62. updateFile('bytecode', $bytecodev);
  63. # ================== Subroutines ==================
  64. # Retrieve TXT record for a given DNS name
  65. sub getTXT {
  66. my $domain = shift;
  67. my $res = Net::DNS::Resolver->new;
  68. my $txt_query = $res->query($domain, "TXT");
  69. if ($txt_query) {
  70. return ($txt_query->answer)[0]->txtdata;
  71. } else {
  72. warn "Unable to get TXT Record: ", $res->errorstring, "\n";
  73. return 0;
  74. }
  75. }
  76. # Extract local CVD version using sigtool
  77. sub getLocalVersion {
  78. my $file = shift;
  79. my $cmd = "sigtool -i $clamdb/$file.cvd 2>/dev/null";
  80. open my $pipe, '-|', $cmd or die "Can't run $cmd : $!";
  81. while (<$pipe>) {
  82. if (/Version: (\d+)/) {
  83. close $pipe;
  84. return $1;
  85. }
  86. }
  87. close $pipe;
  88. return -1;
  89. }
  90. # Download a full .cvd file with mirror fallback and If-Modified-Since support
  91. sub download_file {
  92. my ($filename, $local_file) = @_;
  93. for my $mirror (@cvd_mirrors) {
  94. my $url = "$mirror/$filename";
  95. print "Trying $url ...\n";
  96. my $ua = LWP::UserAgent->new(
  97. agent => $user_agent,
  98. timeout => 30,
  99. ssl_opts => { verify_hostname => 1 }
  100. );
  101. # Send If-Modified-Since header if file already exists
  102. my $if_modified_since;
  103. if (-e $local_file) {
  104. my $mtime = (stat($local_file))[9];
  105. $if_modified_since = HTTP::Date::time2str($mtime);
  106. }
  107. my $request = HTTP::Request->new(GET => $url);
  108. $request->header('If-Modified-Since' => $if_modified_since) if $if_modified_since;
  109. my $response = $ua->request($request, $local_file);
  110. if ($response->is_success) {
  111. print "✅ Downloaded: $url -> $local_file\n";
  112. return 1;
  113. } elsif ($response->code == 304) {
  114. print "ℹ File not modified: $local_file\n";
  115. return 1;
  116. } else {
  117. warn "⚠ Failed to download $url: " . $response->status_line . "\n";
  118. unlink $local_file if -e $local_file;
  119. }
  120. }
  121. warn "❌ All CVD mirrors failed for $filename\n";
  122. return 0;
  123. }
  124. # Download a .cdiff incremental update file
  125. sub download_cdiff {
  126. my ($filename, $local_file) = @_;
  127. for my $mirror (@cdiff_mirrors) {
  128. my $url = "$mirror/$filename";
  129. print "Trying CDIFF $url ...\n";
  130. my $ua = LWP::UserAgent->new(
  131. agent => $user_agent,
  132. timeout => 30,
  133. ssl_opts => { verify_hostname => 1 }
  134. );
  135. my $response = $ua->get($url);
  136. if ($response->is_success) {
  137. open my $out, '>', $local_file or die "Can't write $local_file: $!";
  138. print $out $response->content;
  139. close $out;
  140. print "✅ Downloaded CDIFF: $url -> $local_file\n";
  141. return 1;
  142. } elsif ($response->code == 404) {
  143. print "ℹ CDIFF not found (404): $url\n";
  144. next;
  145. } else {
  146. warn "⚠ Failed to download CDIFF $url: " . $response->status_line . "\n";
  147. next;
  148. }
  149. }
  150. print "❌ CDIFF $filename not available on any mirror\n";
  151. return 0;
  152. }
  153. # Update a database using incremental CDIFFs when possible,
  154. # otherwise fall back to full CVD download
  155. sub updateFile {
  156. my ($file, $currentversion) = @_;
  157. my $old = 0;
  158. # If file does not exist, download full CVD
  159. if (! -e "$file.cvd") {
  160. warn "file $file.cvd does not exist, downloading full version...\n";
  161. if (download_file("$file.cvd", "temp/$file.cvd")) {
  162. if (-e "temp/$file.cvd" && ! -z "temp/$file.cvd") {
  163. move("temp/$file.cvd", "$file.cvd") or warn "Move failed: $!";
  164. } else {
  165. warn "Downloaded $file.cvd is invalid!\n";
  166. unlink "temp/$file.cvd" if -e "temp/$file.cvd";
  167. }
  168. }
  169. return;
  170. }
  171. # If existing file is valid, try incremental update
  172. if (! -z "$file.cvd") {
  173. $old = getLocalVersion($file);
  174. if ($old > 0 && $old < $currentversion) {
  175. print "$file old: $old current: $currentversion\n";
  176. my @missing_diffs;
  177. # Attempt to download all required CDIFFs
  178. for (my $count = $old + 1; $count <= $currentversion; $count++) {
  179. my $key = "$file:$count";
  180. if ($cdiff_history{$key}) {
  181. print "Skipping (known missing): $file-$count.cdiff\n";
  182. push @missing_diffs, $count;
  183. next;
  184. }
  185. my $cdiff_file = "$file-$count.cdiff";
  186. my $cdiff_result = download_cdiff($cdiff_file, $cdiff_file);
  187. if ($cdiff_result == 0) {
  188. # Mark missing CDIFF to avoid retrying in future runs
  189. $cdiff_history{$key} = 1;
  190. save_cdiff_history();
  191. push @missing_diffs, $count;
  192. }
  193. }
  194. # If any CDIFFs are missing, fall back to full CVD update
  195. if (@missing_diffs) {
  196. print "Incremental update not possible for $file (missing: @missing_diffs), falling back to full CVD\n";
  197. for my $c ($old + 1 .. $currentversion) {
  198. unlink "$file-$c.cdiff" if -e "$file-$c.cdiff";
  199. }
  200. copy("$file.cvd", "temp/$file.cvd") or warn "Copy failed: $!";
  201. if (download_file("$file.cvd", "temp/$file.cvd")) {
  202. if (-e "temp/$file.cvd" && ! -z "temp/$file.cvd") {
  203. if ((stat("temp/$file.cvd"))[9] > (stat("$file.cvd"))[9]) {
  204. move("temp/$file.cvd", "$file.cvd") or warn "Move failed: $!";
  205. } else {
  206. unlink "temp/$file.cvd";
  207. }
  208. } else {
  209. warn "Full $file.cvd is invalid after download!\n";
  210. unlink "temp/$file.cvd" if -e "temp/$file.cvd";
  211. }
  212. }
  213. return;
  214. }
  215. }
  216. } else {
  217. # Zero-sized file, re-download full version
  218. warn "file $file.cvd is zero-sized, downloading full version\n";
  219. download_file("$file.cvd", "temp/$file.cvd");
  220. if (-e "temp/$file.cvd" && ! -z "temp/$file.cvd") {
  221. move("temp/$file.cvd", "$file.cvd") or warn "Move failed: $!";
  222. }
  223. return;
  224. }
  225. # No version change
  226. return if ($currentversion == $old);
  227. # Full update if needed
  228. copy("$file.cvd", "temp/$file.cvd") or warn "Copy failed: $!";
  229. if (download_file("$file.cvd", "temp/$file.cvd")) {
  230. if (-e "temp/$file.cvd" && ! -z "temp/$file.cvd") {
  231. if ((stat("temp/$file.cvd"))[9] > (stat("$file.cvd"))[9]) {
  232. print "file temp/$file.cvd is newer than $file.cvd\n";
  233. move("temp/$file.cvd", "$file.cvd") or warn "Move failed: $!";
  234. } else {
  235. unlink "temp/$file.cvd";
  236. }
  237. } else {
  238. warn "temp/$file.cvd is not valid, not copying back!\n";
  239. unlink "temp/$file.cvd";
  240. }
  241. }
  242. }
  243. # Download only the latest CDIFF and record if missing
  244. sub updateFileCdiff {
  245. my ($file, $currentversion) = @_;
  246. my $fullname = "$file-$currentversion.cdiff";
  247. my $key = "$file:$currentversion";
  248. return if $cdiff_history{$key};
  249. if (! -e $fullname) {
  250. my $result = download_cdiff($fullname, $fullname);
  251. if ($result == 0) {
  252. $cdiff_history{$key} = 1;
  253. save_cdiff_history();
  254. }
  255. }
  256. }
  257. # --------------------------- CDIFF HISTORY HANDLING ---------------------------
  258. # Load list of known-missing CDIFFs from disk
  259. sub load_cdiff_history {
  260. my $hist_file = "$clamdb/cdiff_history.txt";
  261. return unless -e $hist_file;
  262. open my $fh, '<', $hist_file or warn "Can't read history: $!";
  263. while (my $line = <$fh>) {
  264. chomp $line;
  265. $line =~ s/^\s+|\s+$//g;
  266. next if $line eq '' || $line =~ /^#/;
  267. $cdiff_history{$line} = 1;
  268. }
  269. close $fh;
  270. }
  271. # Save known-missing CDIFFs to disk
  272. sub save_cdiff_history {
  273. my $hist_file = "$clamdb/cdiff_history.txt";
  274. my @lines = sort keys %cdiff_history;
  275. open my $fh, '>', $hist_file or die "Can't write history: $!";
  276. print $fh "$_\n" for @lines;
  277. close $fh;
  278. }
  279. __END__