]>
Commit | Line | Data |
---|---|---|
758c7b6b DM |
1 | package PMG::Utils; |
2 | ||
3 | use strict; | |
4 | use warnings; | |
2808da9f | 5 | use Cwd; |
758c7b6b | 6 | use DBI; |
b8ea5d5d | 7 | use Net::Cmd; |
758c7b6b | 8 | use Net::SMTP; |
26357b0a | 9 | use IO::File; |
cad3d400 | 10 | use File::stat; |
d17c5265 DM |
11 | use POSIX qw(strftime); |
12 | use File::stat; | |
ff1c5a81 | 13 | use File::Basename; |
972a3b0e | 14 | use MIME::Entity; |
758c7b6b DM |
15 | use MIME::Words; |
16 | use MIME::Parser; | |
8210c7fa | 17 | use Time::HiRes qw (gettimeofday); |
2f7031b7 | 18 | use Time::Local; |
26357b0a | 19 | use Xdgmime; |
d0d91cda | 20 | use Data::Dumper; |
62ebb4bc | 21 | use Digest::SHA; |
5d5af7c5 | 22 | use Digest::MD5; |
f609bf7f | 23 | use Net::IP; |
9f67f5b3 | 24 | use Socket; |
dff363d9 DM |
25 | use RRDs; |
26 | use Filesys::Df; | |
8208c076 | 27 | use Encode; |
00eaaf69 DM |
28 | use utf8; |
29 | no utf8; | |
30 | ||
9a56f771 | 31 | use HTML::Entities; |
16ad0786 | 32 | use JSON; |
758c7b6b | 33 | |
dff363d9 | 34 | use PVE::ProcFSTools; |
f609bf7f | 35 | use PVE::Network; |
5953119e | 36 | use PVE::Tools; |
758c7b6b | 37 | use PVE::SafeSyslog; |
f609bf7f | 38 | use PVE::ProcFSTools; |
d0d91cda | 39 | use PMG::AtomicFile; |
8210c7fa | 40 | use PMG::MailQueue; |
c4df1b85 | 41 | use PMG::SMTPPrinter; |
18598b2c | 42 | use PMG::MIMEUtils; |
758c7b6b | 43 | |
6529020a SI |
44 | use base 'Exporter'; |
45 | ||
46 | our @EXPORT_OK = qw( | |
47 | postgres_admin_cmd | |
639b28e6 | 48 | try_decode_utf8 |
6529020a SI |
49 | ); |
50 | ||
6c54c10a | 51 | my $valid_pmg_realms = ['pam', 'pmg', 'quarantine']; |
62ebb4bc DM |
52 | |
53 | PVE::JSONSchema::register_standard_option('realm', { | |
54 | description => "Authentication domain ID", | |
6c54c10a DM |
55 | type => 'string', |
56 | enum => $valid_pmg_realms, | |
62ebb4bc DM |
57 | maxLength => 32, |
58 | }); | |
59 | ||
6214b5cf DM |
60 | PVE::JSONSchema::register_standard_option('pmg-starttime', { |
61 | description => "Only consider entries newer than 'starttime' (unix epoch). Default is 'now - 1day'.", | |
62 | type => 'integer', | |
63 | minimum => 0, | |
64 | optional => 1, | |
65 | }); | |
66 | ||
67 | PVE::JSONSchema::register_standard_option('pmg-endtime', { | |
68 | description => "Only consider entries older than 'endtime' (unix epoch). This is set to '<start> + 1day' by default.", | |
69 | type => 'integer', | |
70 | minimum => 1, | |
71 | optional => 1, | |
72 | }); | |
73 | ||
62ebb4bc DM |
74 | PVE::JSONSchema::register_format('pmg-userid', \&verify_username); |
75 | sub verify_username { | |
76 | my ($username, $noerr) = @_; | |
77 | ||
78 | $username = '' if !$username; | |
79 | my $len = length($username); | |
80 | if ($len < 3) { | |
81 | die "user name '$username' is too short\n" if !$noerr; | |
82 | return undef; | |
83 | } | |
84 | if ($len > 64) { | |
85 | die "user name '$username' is too long ($len > 64)\n" if !$noerr; | |
86 | return undef; | |
87 | } | |
88 | ||
89 | # we only allow a limited set of characters | |
90 | # colon is not allowed, because we store usernames in | |
91 | # colon separated lists)! | |
92 | # slash is not allowed because it is used as pve API delimiter | |
93 | # also see "man useradd" | |
6c54c10a DM |
94 | my $realm_list = join('|', @$valid_pmg_realms); |
95 | if ($username =~ m!^([^\s:/]+)\@(${realm_list})$!) { | |
62ebb4bc DM |
96 | return wantarray ? ($username, $1, $2) : $username; |
97 | } | |
98 | ||
99 | die "value '$username' does not look like a valid user name\n" if !$noerr; | |
100 | ||
101 | return undef; | |
102 | } | |
103 | ||
104 | PVE::JSONSchema::register_standard_option('userid', { | |
105 | description => "User ID", | |
106 | type => 'string', format => 'pmg-userid', | |
6b0180c3 | 107 | minLength => 4, |
62ebb4bc | 108 | maxLength => 64, |
6b0180c3 | 109 | }); |
62ebb4bc DM |
110 | |
111 | PVE::JSONSchema::register_standard_option('username', { | |
112 | description => "Username (without realm)", | |
113 | type => 'string', | |
114 | pattern => '[^\s:\/\@]{3,60}', | |
6b0180c3 | 115 | minLength => 4, |
62ebb4bc DM |
116 | maxLength => 64, |
117 | }); | |
118 | ||
01929101 DM |
119 | PVE::JSONSchema::register_standard_option('pmg-email-address', { |
120 | description => "Email Address (allow most characters).", | |
121 | type => 'string', | |
959e331c | 122 | pattern => '(?:[^\s\\\@]+\@[^\s\/\\\@]+)', |
01929101 DM |
123 | maxLength => 512, |
124 | minLength => 3, | |
125 | }); | |
126 | ||
1a1bde13 DC |
127 | PVE::JSONSchema::register_standard_option('pmg-whiteblacklist-entry-list', { |
128 | description => "White/Blacklist entry list (allow most characters). Can contain globs", | |
129 | type => 'string', | |
130 | pattern => '(?:[^\s\/\\\;\,]+)(?:\,[^\s\/\\\;\,]+)*', | |
131 | minLength => 3, | |
132 | }); | |
133 | ||
758c7b6b DM |
134 | sub lastid { |
135 | my ($dbh, $seq) = @_; | |
136 | ||
137 | return $dbh->last_insert_id( | |
138 | undef, undef, undef, undef, { sequence => $seq}); | |
139 | } | |
140 | ||
ab466078 DM |
141 | # quote all regex operators |
142 | sub quote_regex { | |
143 | my $val = shift; | |
144 | ||
145 | $val =~ s/([\(\)\[\]\/\}\+\*\?\.\|\^\$\\])/\\$1/g; | |
146 | ||
147 | return $val; | |
148 | } | |
149 | ||
cad3d400 DM |
150 | sub file_older_than { |
151 | my ($filename, $lasttime) = @_; | |
152 | ||
153 | my $st = stat($filename); | |
154 | ||
155 | return 0 if !defined($st); | |
156 | ||
157 | return ($lasttime >= $st->ctime); | |
158 | } | |
159 | ||
758c7b6b DM |
160 | sub extract_filename { |
161 | my ($head) = @_; | |
162 | ||
163 | if (my $value = $head->recommended_filename()) { | |
8210c7fa | 164 | chomp $value; |
758c7b6b DM |
165 | if (my $decvalue = MIME::Words::decode_mimewords($value)) { |
166 | $decvalue =~ s/\0/ /g; | |
5953119e | 167 | $decvalue = PVE::Tools::trim($decvalue); |
758c7b6b DM |
168 | return $decvalue; |
169 | } | |
170 | } | |
171 | ||
172 | return undef; | |
173 | } | |
174 | ||
175 | sub remove_marks { | |
18598b2c | 176 | my ($entity, $add_id) = @_; |
758c7b6b | 177 | |
18598b2c | 178 | my $id = 1; |
758c7b6b | 179 | |
18598b2c DC |
180 | PMG::MIMEUtils::traverse_mime_parts($entity, sub { |
181 | my ($part) = @_; | |
182 | foreach my $tag (grep {/^x-proxmox-tmp/i} $part->head->tags) { | |
183 | $part->head->delete($tag); | |
184 | } | |
758c7b6b | 185 | |
18598b2c | 186 | $part->head->replace('X-Proxmox-tmp-AID', $id) if $add_id; |
758c7b6b | 187 | |
18598b2c DC |
188 | $id++; |
189 | }); | |
758c7b6b DM |
190 | } |
191 | ||
192 | sub subst_values { | |
193 | my ($body, $dh) = @_; | |
194 | ||
195 | return if !$body; | |
196 | ||
197 | foreach my $k (keys %$dh) { | |
198 | my $v = $dh->{$k}; | |
bd98f5a1 DM |
199 | if (defined($v)) { |
200 | $body =~ s/__\Q${k}\E__/$v/gs; | |
758c7b6b DM |
201 | } |
202 | } | |
203 | ||
204 | return $body; | |
205 | } | |
206 | ||
3650871c SI |
207 | sub subst_values_for_header { |
208 | my ($header, $dh) = @_; | |
209 | ||
210 | my $res = ''; | |
211 | foreach my $line (split('\r?\n\s*', subst_values ($header, $dh))) { | |
212 | $res .= "\n" if $res; | |
213 | $res .= MIME::Words::encode_mimewords(encode('UTF-8', $line), 'Charset' => 'UTF-8'); | |
214 | } | |
215 | ||
216 | # support for multiline values (i.e. __SPAM_INFO__) | |
217 | $res =~ s/\n/\n\t/sg; # indent content | |
218 | $res =~ s/\n\s*\n//sg; # remove empty line | |
219 | $res =~ s/\n?\s*$//s; # remove trailing spaces | |
220 | ||
221 | return $res; | |
222 | } | |
223 | ||
758c7b6b | 224 | sub reinject_mail { |
ad1c6bce | 225 | my ($entity, $sender, $targets, $xforward, $me, $params) = @_; |
758c7b6b DM |
226 | |
227 | my $smtp; | |
228 | my $resid; | |
229 | my $rescode; | |
230 | my $resmess; | |
231 | ||
232 | eval { | |
ebd31d3e | 233 | my $smtp = Net::SMTP->new('::FFFF:127.0.0.1', Port => 10025, Hello => $me) || |
758c7b6b DM |
234 | die "unable to connect to localhost at port 10025"; |
235 | ||
236 | if (defined($xforward)) { | |
237 | my $xfwd; | |
8210c7fa | 238 | |
758c7b6b DM |
239 | foreach my $attr (keys %{$xforward}) { |
240 | $xfwd .= " $attr=$xforward->{$attr}"; | |
241 | } | |
242 | ||
243 | if ($xfwd && $smtp->command("XFORWARD", $xfwd)->response() != CMD_OK) { | |
244 | syslog('err', "xforward error - got: %s %s", $smtp->code, scalar($smtp->message)); | |
245 | } | |
246 | } | |
247 | ||
00eaaf69 DM |
248 | my $has_utf8_targets = 0; |
249 | foreach my $target (@$targets) { | |
250 | if (utf8::is_utf8($target)) { | |
251 | $has_utf8_targets = 1; | |
252 | last; | |
253 | } | |
254 | } | |
255 | ||
256 | my $mail_opts = " BODY=8BITMIME"; | |
257 | my $sender_addr; | |
258 | if (utf8::is_utf8($sender)) { | |
259 | $sender_addr = encode('UTF-8', $smtp->_addr($sender)); | |
260 | $mail_opts .= " SMTPUTF8"; | |
261 | } else { | |
262 | $sender_addr = $smtp->_addr($sender); | |
263 | $mail_opts .= " SMTPUTF8" if $has_utf8_targets; | |
264 | } | |
265 | ||
ad1c6bce SI |
266 | if (defined($params->{mail})) { |
267 | my $mailparams = $params->{mail}; | |
268 | for my $p (keys %$mailparams) { | |
269 | $mail_opts .= " $p=$mailparams->{$p}"; | |
270 | } | |
271 | } | |
272 | ||
00eaaf69 | 273 | if (!$smtp->_MAIL("FROM:" . $sender_addr . $mail_opts)) { |
758c7b6b DM |
274 | syslog('err', "smtp error - got: %s %s", $smtp->code, scalar ($smtp->message)); |
275 | die "smtp from: ERROR"; | |
276 | } | |
277 | ||
00eaaf69 DM |
278 | foreach my $target (@$targets) { |
279 | my $rcpt_addr; | |
ad1c6bce SI |
280 | my $rcpt_opts = ''; |
281 | if (defined($params->{rcpt}->{$target})) { | |
282 | my $rcptparams = $params->{rcpt}->{$target}; | |
283 | for my $p (keys %$rcptparams) { | |
284 | $rcpt_opts .= " $p=$rcptparams->{$p}"; | |
285 | } | |
286 | } | |
287 | ||
00eaaf69 DM |
288 | if (utf8::is_utf8($target)) { |
289 | $rcpt_addr = encode('UTF-8', $smtp->_addr($target)); | |
290 | } else { | |
291 | $rcpt_addr = $smtp->_addr($target); | |
292 | } | |
293 | if (!$smtp->_RCPT("TO:" . $rcpt_addr . $rcpt_opts)) { | |
294 | syslog ('err', "smtp error - got: %s %s", $smtp->code, scalar($smtp->message)); | |
295 | die "smtp to: ERROR"; | |
296 | } | |
758c7b6b DM |
297 | } |
298 | ||
299 | # Output the head: | |
300 | #$entity->sync_headers (); | |
301 | $smtp->data(); | |
302 | ||
303 | my $out = PMG::SMTPPrinter->new($smtp); | |
304 | $entity->print($out); | |
8210c7fa DM |
305 | |
306 | # make sure we always have a newline at the end of the mail | |
758c7b6b DM |
307 | # else dataend() fails |
308 | $smtp->datasend("\n"); | |
309 | ||
310 | if ($smtp->dataend()) { | |
311 | my @msgs = $smtp->message; | |
8210c7fa DM |
312 | $resmess = $msgs[$#msgs]; |
313 | ($resid) = $resmess =~ m/Ok: queued as ([0-9A-Z]+)/; | |
758c7b6b DM |
314 | $rescode = $smtp->code; |
315 | if (!$resid) { | |
316 | die sprintf("unexpected SMTP result - got: %s %s : WARNING", $smtp->code, $resmess); | |
8210c7fa | 317 | } |
758c7b6b DM |
318 | } else { |
319 | my @msgs = $smtp->message; | |
8210c7fa | 320 | $resmess = $msgs[$#msgs]; |
758c7b6b DM |
321 | $rescode = $smtp->code; |
322 | die sprintf("sending data failed - got: %s %s : ERROR", $smtp->code, $resmess); | |
323 | } | |
324 | }; | |
325 | my $err = $@; | |
8210c7fa | 326 | |
758c7b6b | 327 | $smtp->quit if $smtp; |
8210c7fa | 328 | |
758c7b6b DM |
329 | if ($err) { |
330 | syslog ('err', $err); | |
331 | } | |
332 | ||
333 | return wantarray ? ($resid, $rescode, $resmess) : $resid; | |
334 | } | |
335 | ||
89d4d155 SI |
336 | sub analyze_custom_check { |
337 | my ($queue, $dname, $pmg_cfg) = @_; | |
338 | ||
339 | my $enable_custom_check = $pmg_cfg->get('admin', 'custom_check'); | |
340 | return undef if !$enable_custom_check; | |
341 | ||
342 | my $timeout = 60*5; | |
343 | my $customcheck_exe = $pmg_cfg->get('admin', 'custom_check_path'); | |
344 | my $customcheck_apiver = 'v1'; | |
345 | my ($csec, $usec) = gettimeofday(); | |
346 | ||
347 | my $vinfo; | |
348 | my $spam_score; | |
349 | ||
350 | eval { | |
351 | ||
352 | my $log_err = sub { | |
353 | my ($errmsg) = @_; | |
354 | $errmsg =~ s/%/%%/; | |
355 | syslog('err', $errmsg); | |
356 | }; | |
357 | ||
358 | my $customcheck_output_apiver; | |
359 | my $have_result; | |
360 | my $parser = sub { | |
361 | my ($line) = @_; | |
362 | ||
363 | my $result_flag; | |
364 | if ($line =~ /^v\d$/) { | |
365 | die "api version already defined!\n" if defined($customcheck_output_apiver); | |
366 | $customcheck_output_apiver = $line; | |
367 | die "api version mismatch - expected $customcheck_apiver, got $customcheck_output_apiver !\n" | |
368 | if ($customcheck_output_apiver ne $customcheck_apiver); | |
369 | } elsif ($line =~ /^SCORE: (-?[0-9]+|.[0-9]+|[0-9]+.[0-9]+)$/) { | |
370 | $spam_score = $1; | |
371 | $result_flag = 1; | |
372 | } elsif ($line =~ /^VIRUS: (.+)$/) { | |
373 | $vinfo = $1; | |
374 | $result_flag = 1; | |
375 | } elsif ($line =~ /^OK$/) { | |
376 | $result_flag = 1; | |
377 | } else { | |
378 | die "got unexpected output!\n"; | |
379 | } | |
380 | die "got more than 1 result outputs\n" if ( $have_result && $result_flag); | |
381 | $have_result = $result_flag; | |
382 | }; | |
383 | ||
384 | PVE::Tools::run_command([$customcheck_exe, $customcheck_apiver, $dname], | |
385 | errmsg => "$queue->{logid} custom check error", | |
386 | errfunc => $log_err, outfunc => $parser, timeout => $timeout); | |
387 | ||
388 | die "no api version returned\n" if !defined($customcheck_output_apiver); | |
389 | die "no result output!\n" if !$have_result; | |
390 | }; | |
391 | my $err = $@; | |
392 | ||
393 | if ($vinfo) { | |
394 | syslog('info', "$queue->{logid}: virus detected: $vinfo (custom)"); | |
395 | } | |
396 | ||
397 | my ($csec_end, $usec_end) = gettimeofday(); | |
398 | $queue->{ptime_custom} = | |
399 | int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000); | |
400 | ||
401 | if ($err) { | |
402 | syslog ('err', $err); | |
403 | $vinfo = undef; | |
404 | $queue->{errors} = 1; | |
405 | } | |
406 | ||
407 | $queue->{vinfo_custom} = $vinfo; | |
408 | $queue->{spam_custom} = $spam_score; | |
409 | ||
410 | return ($vinfo, $spam_score); | |
411 | } | |
412 | ||
8210c7fa DM |
413 | sub analyze_virus_clam { |
414 | my ($queue, $dname, $pmg_cfg) = @_; | |
415 | ||
416 | my $timeout = 60*5; | |
417 | my $vinfo; | |
418 | ||
419 | my $clamdscan_opts = "--stdout"; | |
420 | ||
421 | my ($csec, $usec) = gettimeofday(); | |
422 | ||
423 | my $previous_alarm; | |
424 | ||
425 | eval { | |
426 | ||
427 | $previous_alarm = alarm($timeout); | |
428 | ||
429 | $SIG{ALRM} = sub { | |
430 | die "$queue->{logid}: Maximum time ($timeout sec) exceeded. " . | |
431 | "virus analyze (clamav) failed: ERROR"; | |
432 | }; | |
433 | ||
434 | open(CMD, "/usr/bin/clamdscan $clamdscan_opts '$dname'|") || | |
435 | die "$queue->{logid}: can't exec clamdscan: $! : ERROR"; | |
436 | ||
437 | my $ifiles; | |
8210c7fa | 438 | |
54eaf7df DM |
439 | my $response = ''; |
440 | while (defined(my $line = <CMD>)) { | |
441 | if ($line =~ m/^$dname.*:\s+([^ :]*)\s+FOUND$/) { | |
8210c7fa DM |
442 | # we just use the first detected virus name |
443 | $vinfo = $1 if !$vinfo; | |
54eaf7df | 444 | } elsif ($line =~ m/^Infected files:\s(\d*)$/i) { |
8210c7fa DM |
445 | $ifiles = $1; |
446 | } | |
447 | ||
54eaf7df | 448 | $response .= $line; |
8210c7fa DM |
449 | } |
450 | ||
451 | close(CMD); | |
452 | ||
453 | alarm(0); # avoid race conditions | |
454 | ||
455 | if (!defined($ifiles)) { | |
456 | die "$queue->{logid}: got undefined output from " . | |
54eaf7df | 457 | "virus detector: $response : ERROR"; |
8210c7fa DM |
458 | } |
459 | ||
460 | if ($vinfo) { | |
54eaf7df | 461 | syslog('info', "$queue->{logid}: virus detected: $vinfo (clamav)"); |
8210c7fa DM |
462 | } |
463 | }; | |
464 | my $err = $@; | |
465 | ||
466 | alarm($previous_alarm); | |
467 | ||
468 | my ($csec_end, $usec_end) = gettimeofday(); | |
469 | $queue->{ptime_clam} = | |
470 | int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000); | |
471 | ||
472 | if ($err) { | |
473 | syslog ('err', $err); | |
474 | $vinfo = undef; | |
475 | $queue->{errors} = 1; | |
476 | } | |
477 | ||
478 | $queue->{vinfo_clam} = $vinfo; | |
479 | ||
480 | return $vinfo ? "$vinfo (clamav)" : undef; | |
481 | } | |
482 | ||
6ccbc37f DM |
483 | sub analyze_virus_avast { |
484 | my ($queue, $dname, $pmg_cfg) = @_; | |
485 | ||
486 | my $timeout = 60*5; | |
487 | my $vinfo; | |
488 | ||
489 | my ($csec, $usec) = gettimeofday(); | |
490 | ||
491 | my $previous_alarm; | |
492 | ||
493 | eval { | |
494 | ||
495 | $previous_alarm = alarm($timeout); | |
496 | ||
497 | $SIG{ALRM} = sub { | |
498 | die "$queue->{logid}: Maximum time ($timeout sec) exceeded. " . | |
499 | "virus analyze (avast) failed: ERROR"; | |
500 | }; | |
501 | ||
661d569a | 502 | open(my $cmd, '-|', 'scan', $dname) || |
6ccbc37f DM |
503 | die "$queue->{logid}: can't exec avast scan: $! : ERROR"; |
504 | ||
505 | my $response = ''; | |
506 | while (defined(my $line = <$cmd>)) { | |
507 | if ($line =~ m/^$dname\s+(.*\S)\s*$/) { | |
508 | # we just use the first detected virus name | |
509 | $vinfo = $1 if !$vinfo; | |
510 | } | |
511 | ||
512 | $response .= $line; | |
513 | } | |
514 | ||
515 | close($cmd); | |
516 | ||
517 | alarm(0); # avoid race conditions | |
518 | ||
519 | if ($vinfo) { | |
520 | syslog('info', "$queue->{logid}: virus detected: $vinfo (avast)"); | |
521 | } | |
522 | }; | |
523 | my $err = $@; | |
524 | ||
525 | alarm($previous_alarm); | |
526 | ||
527 | my ($csec_end, $usec_end) = gettimeofday(); | |
528 | $queue->{ptime_clam} = | |
529 | int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000); | |
530 | ||
531 | if ($err) { | |
532 | syslog ('err', $err); | |
533 | $vinfo = undef; | |
534 | $queue->{errors} = 1; | |
535 | } | |
536 | ||
537 | return undef if !$vinfo; | |
538 | ||
539 | $queue->{vinfo_avast} = $vinfo; | |
540 | ||
541 | return "$vinfo (avast)"; | |
542 | } | |
543 | ||
8210c7fa DM |
544 | sub analyze_virus { |
545 | my ($queue, $filename, $pmg_cfg, $testmode) = @_; | |
546 | ||
547 | # TODO: support other virus scanners? | |
548 | ||
6ccbc37f DM |
549 | if ($testmode) { |
550 | my $vinfo_clam = analyze_virus_clam($queue, $filename, $pmg_cfg); | |
551 | my $vinfo_avast = analyze_virus_avast($queue, $filename, $pmg_cfg); | |
552 | ||
553 | return $vinfo_avast || $vinfo_clam; | |
554 | } | |
555 | ||
556 | my $enable_avast = $pmg_cfg->get('admin', 'avast'); | |
557 | ||
558 | if ($enable_avast) { | |
559 | if (my $vinfo = analyze_virus_avast($queue, $filename, $pmg_cfg)) { | |
560 | return $vinfo; | |
561 | } | |
562 | } | |
563 | ||
9acd4d57 DM |
564 | my $enable_clamav = $pmg_cfg->get('admin', 'clamav'); |
565 | ||
566 | if ($enable_clamav) { | |
567 | if (my $vinfo = analyze_virus_clam($queue, $filename, $pmg_cfg)) { | |
568 | return $vinfo; | |
569 | } | |
570 | } | |
571 | ||
572 | return undef; | |
8210c7fa DM |
573 | } |
574 | ||
26357b0a DM |
575 | sub magic_mime_type_for_file { |
576 | my ($filename) = @_; | |
dff363d9 | 577 | |
26357b0a DM |
578 | # we do not use get_mime_type_for_file, because that considers |
579 | # filename extensions - we only want magic type detection | |
580 | ||
581 | my $bufsize = Xdgmime::xdg_mime_get_max_buffer_extents(); | |
582 | die "got strange value for max_buffer_extents" if $bufsize > 4096*10; | |
583 | ||
584 | my $ct = "application/octet-stream"; | |
585 | ||
dff363d9 | 586 | my $fh = IO::File->new("<$filename") || |
26357b0a DM |
587 | die "unable to open file '$filename' - $!"; |
588 | ||
589 | my ($buf, $len); | |
590 | if (($len = $fh->read($buf, $bufsize)) > 0) { | |
591 | $ct = xdg_mime_get_mime_type_for_data($buf, $len); | |
592 | } | |
593 | $fh->close(); | |
dff363d9 | 594 | |
26357b0a | 595 | die "unable to read file '$filename' - $!" if ($len < 0); |
dff363d9 | 596 | |
26357b0a DM |
597 | return $ct; |
598 | } | |
758c7b6b | 599 | |
1d4193a1 DM |
600 | sub add_ct_marks { |
601 | my ($entity) = @_; | |
602 | ||
603 | if (my $path = $entity->{PMX_decoded_path}) { | |
604 | ||
605 | # set a reasonable default if magic does not give a result | |
606 | $entity->{PMX_magic_ct} = $entity->head->mime_attr('content-type'); | |
607 | ||
608 | if (my $ct = magic_mime_type_for_file($path)) { | |
609 | if ($ct ne 'application/octet-stream' || !$entity->{PMX_magic_ct}) { | |
610 | $entity->{PMX_magic_ct} = $ct; | |
611 | } | |
612 | } | |
613 | ||
614 | my $filename = $entity->head->recommended_filename; | |
615 | $filename = basename($path) if !defined($filename) || $filename eq ''; | |
616 | ||
617 | if (my $ct = xdg_mime_get_mime_type_from_file_name($filename)) { | |
618 | $entity->{PMX_glob_ct} = $ct; | |
619 | } | |
620 | } | |
621 | ||
622 | foreach my $part ($entity->parts) { | |
623 | add_ct_marks ($part); | |
624 | } | |
625 | } | |
626 | ||
f609bf7f DM |
627 | # x509 certificate utils |
628 | ||
896ef634 DM |
629 | # only write output if something fails |
630 | sub run_silent_cmd { | |
631 | my ($cmd) = @_; | |
632 | ||
633 | my $outbuf = ''; | |
634 | ||
635 | my $record_output = sub { | |
636 | $outbuf .= shift; | |
637 | $outbuf .= "\n"; | |
638 | }; | |
639 | ||
640 | eval { | |
641 | PVE::Tools::run_command($cmd, outfunc => $record_output, | |
642 | errfunc => $record_output); | |
643 | }; | |
644 | my $err = $@; | |
645 | ||
646 | if ($err) { | |
647 | print STDERR $outbuf; | |
648 | die $err; | |
649 | } | |
650 | } | |
651 | ||
3278b571 | 652 | my $proxmox_tls_cert_fn = "/etc/pmg/pmg-tls.pem"; |
f609bf7f DM |
653 | |
654 | sub gen_proxmox_tls_cert { | |
bc44eb02 | 655 | my ($force) = @_; |
f609bf7f | 656 | |
bc44eb02 DM |
657 | my $resolv = PVE::INotify::read_file('resolvconf'); |
658 | my $domain = $resolv->{search}; | |
659 | ||
660 | my $company = $domain; # what else ? | |
661 | my $cn = "*.$domain"; | |
662 | ||
663 | return if !$force && -f $proxmox_tls_cert_fn; | |
f609bf7f DM |
664 | |
665 | my $sslconf = <<__EOD__; | |
666 | RANDFILE = /root/.rnd | |
667 | extensions = v3_req | |
668 | ||
669 | [ req ] | |
670 | default_bits = 4096 | |
671 | distinguished_name = req_distinguished_name | |
672 | req_extensions = v3_req | |
673 | prompt = no | |
674 | string_mask = nombstr | |
675 | ||
676 | [ req_distinguished_name ] | |
677 | organizationalUnitName = Proxmox Mail Gateway | |
678 | organizationName = $company | |
679 | commonName = $cn | |
680 | ||
681 | [ v3_req ] | |
682 | basicConstraints = CA:FALSE | |
683 | nsCertType = server | |
684 | keyUsage = nonRepudiation, digitalSignature, keyEncipherment | |
685 | __EOD__ | |
686 | ||
3278b571 | 687 | my $cfgfn = "/tmp/pmgtlsconf-$$.tmp"; |
f609bf7f DM |
688 | my $fh = IO::File->new ($cfgfn, "w"); |
689 | print $fh $sslconf; | |
690 | close ($fh); | |
691 | ||
692 | eval { | |
896ef634 DM |
693 | my $cmd = ['openssl', 'req', '-batch', '-x509', '-new', '-sha256', |
694 | '-config', $cfgfn, '-days', 3650, '-nodes', | |
695 | '-out', $proxmox_tls_cert_fn, | |
696 | '-keyout', $proxmox_tls_cert_fn]; | |
697 | run_silent_cmd($cmd); | |
f609bf7f DM |
698 | }; |
699 | ||
700 | if (my $err = $@) { | |
701 | unlink $proxmox_tls_cert_fn; | |
702 | unlink $cfgfn; | |
703 | die "unable to generate proxmox certificate request:\n$err"; | |
704 | } | |
705 | ||
706 | unlink $cfgfn; | |
707 | } | |
708 | ||
709 | sub find_local_network_for_ip { | |
1e88a529 | 710 | my ($ip, $noerr) = @_; |
f609bf7f DM |
711 | |
712 | my $testip = Net::IP->new($ip); | |
713 | ||
714 | my $isv6 = $testip->version == 6; | |
715 | my $routes = $isv6 ? | |
716 | PVE::ProcFSTools::read_proc_net_ipv6_route() : | |
717 | PVE::ProcFSTools::read_proc_net_route(); | |
718 | ||
719 | foreach my $entry (@$routes) { | |
720 | my $mask; | |
721 | if ($isv6) { | |
722 | $mask = $entry->{prefix}; | |
723 | next if !$mask; # skip the default route... | |
724 | } else { | |
725 | $mask = $PVE::Network::ipv4_mask_hash_localnet->{$entry->{mask}}; | |
726 | next if !defined($mask); | |
727 | } | |
728 | my $cidr = "$entry->{dest}/$mask"; | |
729 | my $testnet = Net::IP->new($cidr); | |
730 | my $overlap = $testnet->overlaps($testip); | |
731 | if ($overlap == $Net::IP::IP_B_IN_A_OVERLAP || | |
732 | $overlap == $Net::IP::IP_IDENTICAL) | |
733 | { | |
734 | return $cidr; | |
735 | } | |
736 | } | |
737 | ||
1e88a529 DM |
738 | return undef if $noerr; |
739 | ||
f609bf7f DM |
740 | die "unable to detect local network for ip '$ip'\n"; |
741 | } | |
d0d91cda | 742 | |
ef07e4d0 DM |
743 | my $service_aliases = { |
744 | 'postfix' => 'postfix@-', | |
ef07e4d0 DM |
745 | }; |
746 | ||
747 | sub lookup_real_service_name { | |
748 | my $alias = shift; | |
749 | ||
4f06ff8a SI |
750 | if ($alias eq 'postgres') { |
751 | my $pg_ver = get_pg_server_version(); | |
0a05c9d2 | 752 | return "postgresql\@${pg_ver}-main"; |
4f06ff8a SI |
753 | } |
754 | ||
ef07e4d0 DM |
755 | return $service_aliases->{$alias} // $alias; |
756 | } | |
757 | ||
230b4e03 DM |
758 | sub get_full_service_state { |
759 | my ($service) = @_; | |
760 | ||
761 | my $res; | |
762 | ||
763 | my $parser = sub { | |
764 | my $line = shift; | |
765 | if ($line =~ m/^([^=\s]+)=(.*)$/) { | |
766 | $res->{$1} = $2; | |
767 | } | |
768 | }; | |
769 | ||
0a05c9d2 | 770 | $service = lookup_real_service_name($service); |
230b4e03 DM |
771 | PVE::Tools::run_command(['systemctl', 'show', $service], outfunc => $parser); |
772 | ||
773 | return $res; | |
774 | } | |
775 | ||
00d8b7f7 DM |
776 | our $db_service_list = [ |
777 | 'pmgpolicy', 'pmgmirror', 'pmgtunnel', 'pmg-smtp-filter' ]; | |
778 | ||
cfdf6608 DM |
779 | sub service_wait_stopped { |
780 | my ($timeout, $service_list) = @_; | |
781 | ||
782 | my $starttime = time(); | |
783 | ||
784 | foreach my $service (@$service_list) { | |
785 | PVE::Tools::run_command(['systemctl', 'stop', $service]); | |
786 | } | |
787 | ||
788 | while (1) { | |
789 | my $wait = 0; | |
790 | ||
791 | foreach my $service (@$service_list) { | |
792 | my $ss = get_full_service_state($service); | |
793 | my $state = $ss->{ActiveState} // 'unknown'; | |
794 | ||
795 | if ($state ne 'inactive') { | |
796 | if ((time() - $starttime) > $timeout) { | |
797 | syslog('err', "unable to stop services (got timeout)"); | |
798 | $wait = 0; | |
799 | last; | |
800 | } | |
801 | $wait = 1; | |
802 | } | |
803 | } | |
804 | ||
805 | last if !$wait; | |
806 | ||
807 | sleep(1); | |
808 | } | |
809 | } | |
810 | ||
3f85510e DM |
811 | sub service_cmd { |
812 | my ($service, $cmd) = @_; | |
813 | ||
814 | die "unknown service command '$cmd'\n" | |
f6884917 | 815 | if $cmd !~ m/^(start|stop|restart|reload|reload-or-restart)$/; |
3f85510e DM |
816 | |
817 | if ($service eq 'pmgdaemon' || $service eq 'pmgproxy') { | |
822477d5 TL |
818 | die "invalid service cmd '$service $cmd': refusing to stop essential service!\n" |
819 | if $cmd eq 'stop'; | |
81fa07d9 DM |
820 | } elsif ($service eq 'fetchmail') { |
821 | # use restart instead of start - else it does not start 'exited' unit | |
822 | # after setting START_DAEMON=yes in /etc/default/fetchmail | |
823 | $cmd = 'restart' if $cmd eq 'start'; | |
3f85510e DM |
824 | } |
825 | ||
0a05c9d2 | 826 | $service = lookup_real_service_name($service); |
3f85510e DM |
827 | PVE::Tools::run_command(['systemctl', $cmd, $service]); |
828 | }; | |
829 | ||
630d1ae3 DM |
830 | sub run_postmap { |
831 | my ($filename) = @_; | |
832 | ||
833 | # make sure the file exists (else postmap fails) | |
834 | IO::File->new($filename, 'a', 0644); | |
835 | ||
1dc946d4 | 836 | my $mtime_src = (CORE::stat($filename))[9] // |
364f0a6c | 837 | die "unable to read mtime of $filename\n"; |
1dc946d4 DM |
838 | |
839 | my $mtime_dst = (CORE::stat("$filename.db"))[9] // 0; | |
78982d93 DM |
840 | |
841 | # if not changed, do nothing | |
1dc946d4 | 842 | return if $mtime_src <= $mtime_dst; |
78982d93 | 843 | |
630d1ae3 DM |
844 | eval { |
845 | PVE::Tools::run_command( | |
846 | ['/usr/sbin/postmap', $filename], | |
847 | errmsg => "unable to update postfix table $filename"); | |
848 | }; | |
849 | my $err = $@; | |
850 | ||
851 | warn $err if $err; | |
852 | } | |
853 | ||
d17c5265 DM |
854 | sub clamav_dbstat { |
855 | ||
856 | my $res = []; | |
857 | ||
858 | my $read_cvd_info = sub { | |
859 | my ($dbname, $dbfile) = @_; | |
860 | ||
861 | my $header; | |
862 | my $fh = IO::File->new("<$dbfile"); | |
863 | if (!$fh) { | |
1359baef | 864 | warn "can't open ClamAV Database $dbname ($dbfile) - $!\n"; |
d17c5265 DM |
865 | return; |
866 | } | |
867 | $fh->read($header, 512); | |
868 | $fh->close(); | |
869 | ||
870 | ## ClamAV-VDB:16 Mar 2016 23-17 +0000:57:4218790:60:06386f34a16ebeea2733ab037f0536be: | |
871 | if ($header =~ m/^(ClamAV-VDB):([^:]+):(\d+):(\d+):/) { | |
872 | my ($ftype, $btime, $version, $nsigs) = ($1, $2, $3, $4); | |
873 | push @$res, { | |
874 | name => $dbname, | |
875 | type => $ftype, | |
876 | build_time => $btime, | |
877 | version => $version, | |
878 | nsigs => $nsigs, | |
879 | }; | |
880 | } else { | |
881 | warn "unable to parse ClamAV Database $dbname ($dbfile)\n"; | |
882 | } | |
883 | }; | |
884 | ||
885 | # main database | |
886 | my $filename = "/var/lib/clamav/main.inc/main.info"; | |
887 | $filename = "/var/lib/clamav/main.cvd" if ! -f $filename; | |
888 | ||
889 | $read_cvd_info->('main', $filename) if -f $filename; | |
890 | ||
891 | # daily database | |
892 | $filename = "/var/lib/clamav/daily.inc/daily.info"; | |
893 | $filename = "/var/lib/clamav/daily.cvd" if ! -f $filename; | |
894 | $filename = "/var/lib/clamav/daily.cld" if ! -f $filename; | |
895 | ||
896 | $read_cvd_info->('daily', $filename) if -f $filename; | |
897 | ||
898 | $filename = "/var/lib/clamav/bytecode.cvd"; | |
899 | $read_cvd_info->('bytecode', $filename) if -f $filename; | |
900 | ||
dabcd20e DM |
901 | my $ss_dbs_fn = "/var/lib/clamav-unofficial-sigs/configs/ss-include-dbs.txt"; |
902 | my $ss_dbs_files = {}; | |
903 | if (my $ssfh = IO::File->new("<${ss_dbs_fn}")) { | |
904 | while (defined(my $line = <$ssfh>)) { | |
905 | chomp $line; | |
906 | $ss_dbs_files->{$line} = 1; | |
907 | } | |
908 | } | |
d17c5265 DM |
909 | my $last = 0; |
910 | my $nsigs = 0; | |
911 | foreach $filename (</var/lib/clamav/*>) { | |
dabcd20e DM |
912 | my $fn = basename($filename); |
913 | next if !$ss_dbs_files->{$fn}; | |
914 | ||
d17c5265 DM |
915 | my $fh = IO::File->new("<$filename"); |
916 | next if !defined($fh); | |
917 | my $st = stat($fh); | |
918 | next if !$st; | |
919 | my $mtime = $st->mtime(); | |
920 | $last = $mtime if $mtime > $last; | |
921 | while (defined(my $line = <$fh>)) { $nsigs++; } | |
922 | } | |
923 | ||
924 | if ($nsigs > 0) { | |
925 | push @$res, { | |
9860e592 | 926 | name => 'sanesecurity', |
d17c5265 | 927 | type => 'unofficial', |
2d011fef | 928 | build_time => strftime("%d %b %Y %H-%M %z", localtime($last)), |
d17c5265 DM |
929 | nsigs => $nsigs, |
930 | }; | |
931 | } | |
932 | ||
933 | return $res; | |
934 | } | |
935 | ||
dff363d9 DM |
936 | # RRD related code |
937 | my $rrd_dir = "/var/lib/rrdcached/db"; | |
938 | my $rrdcached_socket = "/var/run/rrdcached.sock"; | |
939 | ||
940 | my $rrd_def_node = [ | |
941 | "DS:loadavg:GAUGE:120:0:U", | |
942 | "DS:maxcpu:GAUGE:120:0:U", | |
943 | "DS:cpu:GAUGE:120:0:U", | |
944 | "DS:iowait:GAUGE:120:0:U", | |
945 | "DS:memtotal:GAUGE:120:0:U", | |
946 | "DS:memused:GAUGE:120:0:U", | |
947 | "DS:swaptotal:GAUGE:120:0:U", | |
948 | "DS:swapused:GAUGE:120:0:U", | |
949 | "DS:roottotal:GAUGE:120:0:U", | |
950 | "DS:rootused:GAUGE:120:0:U", | |
951 | "DS:netin:DERIVE:120:0:U", | |
952 | "DS:netout:DERIVE:120:0:U", | |
953 | ||
954 | "RRA:AVERAGE:0.5:1:70", # 1 min avg - one hour | |
955 | "RRA:AVERAGE:0.5:30:70", # 30 min avg - one day | |
956 | "RRA:AVERAGE:0.5:180:70", # 3 hour avg - one week | |
957 | "RRA:AVERAGE:0.5:720:70", # 12 hour avg - one month | |
958 | "RRA:AVERAGE:0.5:10080:70", # 7 day avg - ony year | |
959 | ||
960 | "RRA:MAX:0.5:1:70", # 1 min max - one hour | |
961 | "RRA:MAX:0.5:30:70", # 30 min max - one day | |
962 | "RRA:MAX:0.5:180:70", # 3 hour max - one week | |
963 | "RRA:MAX:0.5:720:70", # 12 hour max - one month | |
964 | "RRA:MAX:0.5:10080:70", # 7 day max - ony year | |
965 | ]; | |
966 | ||
967 | sub cond_create_rrd_file { | |
968 | my ($filename, $rrddef) = @_; | |
969 | ||
970 | return if -f $filename; | |
971 | ||
972 | my @args = ($filename); | |
973 | ||
974 | push @args, "--daemon" => "unix:${rrdcached_socket}" | |
975 | if -S $rrdcached_socket; | |
976 | ||
977 | push @args, '--step', 60; | |
978 | ||
979 | push @args, @$rrddef; | |
980 | ||
981 | # print "TEST: " . join(' ', @args) . "\n"; | |
982 | ||
983 | RRDs::create(@args); | |
984 | my $err = RRDs::error; | |
985 | die "RRD error: $err\n" if $err; | |
986 | } | |
987 | ||
988 | sub update_node_status_rrd { | |
989 | ||
990 | my $filename = "$rrd_dir/pmg-node-v1.rrd"; | |
991 | cond_create_rrd_file($filename, $rrd_def_node); | |
992 | ||
993 | my ($avg1, $avg5, $avg15) = PVE::ProcFSTools::read_loadavg(); | |
994 | ||
995 | my $stat = PVE::ProcFSTools::read_proc_stat(); | |
996 | ||
997 | my $netdev = PVE::ProcFSTools::read_proc_net_dev(); | |
998 | ||
999 | my ($uptime) = PVE::ProcFSTools::read_proc_uptime(); | |
1000 | ||
1001 | my $cpuinfo = PVE::ProcFSTools::read_cpuinfo(); | |
1002 | ||
1003 | my $maxcpu = $cpuinfo->{cpus}; | |
1004 | ||
1005 | # traffic from/to physical interface cards | |
1006 | my $netin = 0; | |
1007 | my $netout = 0; | |
1008 | foreach my $dev (keys %$netdev) { | |
170295f8 | 1009 | next if $dev !~ m/^$PVE::Network::PHYSICAL_NIC_RE$/; |
dff363d9 DM |
1010 | $netin += $netdev->{$dev}->{receive}; |
1011 | $netout += $netdev->{$dev}->{transmit}; | |
1012 | } | |
1013 | ||
1014 | my $meminfo = PVE::ProcFSTools::read_meminfo(); | |
1015 | ||
1016 | my $dinfo = df('/', 1); # output is bytes | |
1017 | ||
1018 | my $ctime = time(); | |
1019 | ||
1020 | # everything not free is considered to be used | |
1021 | my $dused = $dinfo->{blocks} - $dinfo->{bfree}; | |
1022 | ||
1023 | my $data = "$ctime:$avg1:$maxcpu:$stat->{cpu}:$stat->{wait}:" . | |
1024 | "$meminfo->{memtotal}:$meminfo->{memused}:" . | |
1025 | "$meminfo->{swaptotal}:$meminfo->{swapused}:" . | |
1026 | "$dinfo->{blocks}:$dused:$netin:$netout"; | |
1027 | ||
1028 | ||
1029 | my @args = ($filename); | |
1030 | ||
1031 | push @args, "--daemon" => "unix:${rrdcached_socket}" | |
1032 | if -S $rrdcached_socket; | |
1033 | ||
1034 | push @args, $data; | |
1035 | ||
1036 | # print "TEST: " . join(' ', @args) . "\n"; | |
1037 | ||
1038 | RRDs::update(@args); | |
1039 | my $err = RRDs::error; | |
1040 | die "RRD error: $err\n" if $err; | |
1041 | } | |
1042 | ||
065b2986 DM |
1043 | sub create_rrd_data { |
1044 | my ($rrdname, $timeframe, $cf) = @_; | |
1045 | ||
1046 | my $rrd = "${rrd_dir}/$rrdname"; | |
1047 | ||
1048 | my $setup = { | |
1049 | hour => [ 60, 70 ], | |
1050 | day => [ 60*30, 70 ], | |
1051 | week => [ 60*180, 70 ], | |
1052 | month => [ 60*720, 70 ], | |
1053 | year => [ 60*10080, 70 ], | |
1054 | }; | |
1055 | ||
1056 | my ($reso, $count) = @{$setup->{$timeframe}}; | |
1057 | my $ctime = $reso*int(time()/$reso); | |
1058 | my $req_start = $ctime - $reso*$count; | |
1059 | ||
1060 | $cf = "AVERAGE" if !$cf; | |
1061 | ||
1062 | my @args = ( | |
1063 | "-s" => $req_start, | |
1064 | "-e" => $ctime - 1, | |
1065 | "-r" => $reso, | |
1066 | ); | |
1067 | ||
1068 | push @args, "--daemon" => "unix:${rrdcached_socket}" | |
1069 | if -S $rrdcached_socket; | |
1070 | ||
1071 | my ($start, $step, $names, $data) = RRDs::fetch($rrd, $cf, @args); | |
1072 | ||
1073 | my $err = RRDs::error; | |
1074 | die "RRD error: $err\n" if $err; | |
1075 | ||
1076 | die "got wrong time resolution ($step != $reso)\n" | |
1077 | if $step != $reso; | |
1078 | ||
1079 | my $res = []; | |
1080 | my $fields = scalar(@$names); | |
1081 | for my $line (@$data) { | |
1082 | my $entry = { 'time' => $start }; | |
1083 | $start += $step; | |
1084 | for (my $i = 0; $i < $fields; $i++) { | |
1085 | my $name = $names->[$i]; | |
1086 | if (defined(my $val = $line->[$i])) { | |
1087 | $entry->{$name} = $val; | |
1088 | } else { | |
1089 | # leave empty fields undefined | |
1090 | # maybe make this configurable? | |
1091 | } | |
1092 | } | |
1093 | push @$res, $entry; | |
1094 | } | |
1095 | ||
1096 | return $res; | |
1097 | } | |
1098 | ||
8da6f9ec DM |
1099 | sub decode_to_html { |
1100 | my ($charset, $data) = @_; | |
1101 | ||
1102 | my $res = $data; | |
1103 | ||
1104 | eval { $res = encode_entities(decode($charset, $data)); }; | |
1105 | ||
1106 | return $res; | |
1107 | } | |
1108 | ||
15fcd85c | 1109 | # assume enc contains utf-8 and mime-encoded data returns a perl-string (with wide characters) |
46f9e9af DM |
1110 | sub decode_rfc1522 { |
1111 | my ($enc) = @_; | |
1112 | ||
1113 | my $res = ''; | |
1114 | ||
1115 | return '' if !$enc; | |
1116 | ||
1117 | eval { | |
1118 | foreach my $r (MIME::Words::decode_mimewords($enc)) { | |
1119 | my ($d, $cs) = @$r; | |
1120 | if ($d) { | |
1121 | if ($cs) { | |
1122 | $res .= decode($cs, $d); | |
1123 | } else { | |
15fcd85c | 1124 | $res .= try_decode_utf8($d); |
46f9e9af DM |
1125 | } |
1126 | } | |
1127 | } | |
1128 | }; | |
1129 | ||
1130 | $res = $enc if $@; | |
1131 | ||
1132 | return $res; | |
1133 | } | |
1134 | ||
9a56f771 DM |
1135 | sub rfc1522_to_html { |
1136 | my ($enc) = @_; | |
1137 | ||
1138 | my $res = ''; | |
1139 | ||
1140 | return '' if !$enc; | |
1141 | ||
1142 | eval { | |
1143 | foreach my $r (MIME::Words::decode_mimewords($enc)) { | |
1144 | my ($d, $cs) = @$r; | |
1145 | if ($d) { | |
1146 | if ($cs) { | |
6dfa0834 | 1147 | $res .= encode('UTF-8', decode($cs, $d)); |
9a56f771 | 1148 | } else { |
6dfa0834 | 1149 | $res .= $d; |
9a56f771 DM |
1150 | } |
1151 | } | |
1152 | } | |
6dfa0834 | 1153 | $res = encode_entities(decode('UTF-8', $res)); |
9a56f771 DM |
1154 | }; |
1155 | ||
1156 | $res = $enc if $@; | |
1157 | ||
1158 | return $res; | |
1159 | } | |
1160 | ||
9d26ab13 DM |
1161 | # RFC 2047 B-ENCODING http://rfc.net/rfc2047.html |
1162 | # (Q-Encoding is complex and error prone) | |
1163 | sub bencode_header { | |
1164 | my $txt = shift; | |
1165 | ||
1166 | my $CRLF = "\015\012"; | |
1167 | ||
1168 | # Nonprintables (controls + x7F + 8bit): | |
1169 | my $NONPRINT = "\\x00-\\x1F\\x7F-\\xFF"; | |
1170 | ||
1171 | # always use utf-8 (work with japanese character sets) | |
1172 | $txt = encode("UTF-8", $txt); | |
1173 | ||
1174 | return $txt if $txt !~ /[$NONPRINT]/o; | |
1175 | ||
1176 | my $res = ''; | |
1177 | ||
1178 | while ($txt =~ s/^(.{1,42})//sm) { | |
1179 | my $t = MIME::Words::encode_mimeword ($1, 'B', 'UTF-8'); | |
1180 | $res .= $res ? "\015\012\t$t" : $t; | |
1181 | } | |
1182 | ||
1183 | return $res; | |
1184 | } | |
1185 | ||
7d89adf4 | 1186 | sub load_sa_descriptions { |
e325aa6f | 1187 | my ($additional_dirs) = @_; |
7d89adf4 DM |
1188 | |
1189 | my @dirs = ('/usr/share/spamassassin', | |
1190 | '/usr/share/spamassassin-extra'); | |
1191 | ||
e325aa6f DC |
1192 | push @dirs, @$additional_dirs if @$additional_dirs; |
1193 | ||
7d89adf4 DM |
1194 | my $res = {}; |
1195 | ||
1196 | my $parse_sa_file = sub { | |
1197 | my ($file) = @_; | |
1198 | ||
1199 | open(my $fh,'<', $file); | |
1200 | return if !defined($fh); | |
1201 | ||
1202 | while (defined(my $line = <$fh>)) { | |
24780ff0 | 1203 | if ($line =~ m/^(?:\s*)describe\s+(\S+)\s+(.*)\s*$/) { |
7d89adf4 DM |
1204 | my ($name, $desc) = ($1, $2); |
1205 | next if $res->{$name}; | |
1206 | $res->{$name}->{desc} = $desc; | |
1207 | if ($desc =~ m|[\(\s](http:\/\/\S+\.[^\s\.\)]+\.[^\s\.\)]+)|i) { | |
1208 | $res->{$name}->{url} = $1; | |
1209 | } | |
1210 | } | |
1211 | } | |
1212 | close($fh); | |
1213 | }; | |
1214 | ||
1215 | foreach my $dir (@dirs) { | |
1216 | foreach my $file (<$dir/*.cf>) { | |
1217 | $parse_sa_file->($file); | |
1218 | } | |
1219 | } | |
1220 | ||
cda67dee | 1221 | $res->{'ClamAVHeuristics'}->{desc} = "ClamAV heuristic tests"; |
0d5209bf | 1222 | |
7d89adf4 DM |
1223 | return $res; |
1224 | } | |
1225 | ||
8162c745 DM |
1226 | sub format_uptime { |
1227 | my ($uptime) = @_; | |
1228 | ||
1229 | my $days = int($uptime/86400); | |
1230 | $uptime -= $days*86400; | |
1231 | ||
1232 | my $hours = int($uptime/3600); | |
1233 | $uptime -= $hours*3600; | |
1234 | ||
1235 | my $mins = $uptime/60; | |
1236 | ||
1237 | if ($days) { | |
1238 | my $ds = $days > 1 ? 'days' : 'day'; | |
1239 | return sprintf "%d $ds %02d:%02d", $days, $hours, $mins; | |
1240 | } else { | |
1241 | return sprintf "%02d:%02d", $hours, $mins; | |
1242 | } | |
1243 | } | |
1244 | ||
3dfe317a DM |
1245 | sub finalize_report { |
1246 | my ($tt, $template, $data, $mailfrom, $receiver, $debug) = @_; | |
1247 | ||
1248 | my $html = ''; | |
1249 | ||
1250 | $tt->process($template, $data, \$html) || | |
1251 | die $tt->error() . "\n"; | |
1252 | ||
1253 | my $title; | |
1254 | if ($html =~ m|^\s*<title>(.*)</title>|m) { | |
1255 | $title = $1; | |
1256 | } else { | |
1257 | die "unable to extract template title\n"; | |
1258 | } | |
1259 | ||
1260 | my $top = MIME::Entity->build( | |
1261 | Type => "multipart/related", | |
6dfa0834 | 1262 | To => $data->{pmail_raw}, |
3dfe317a DM |
1263 | From => $mailfrom, |
1264 | Subject => bencode_header(decode_entities($title))); | |
1265 | ||
1266 | $top->attach( | |
1267 | Data => $html, | |
1268 | Type => "text/html", | |
1269 | Encoding => $debug ? 'binary' : 'quoted-printable'); | |
1270 | ||
1271 | if ($debug) { | |
1272 | $top->print(); | |
1273 | return; | |
1274 | } | |
1359baef | 1275 | # we use an empty envelope sender (we don't want to receive NDRs) |
3dfe317a DM |
1276 | PMG::Utils::reinject_mail ($top, '', [$receiver], undef, $data->{fqdn}); |
1277 | } | |
1278 | ||
2f7031b7 DM |
1279 | sub lookup_timespan { |
1280 | my ($timespan) = @_; | |
1281 | ||
1282 | my (undef, undef, undef, $mday, $mon, $year) = localtime(time()); | |
1283 | my $daystart = timelocal(0, 0, 0, $mday, $mon, $year); | |
1284 | ||
1285 | my $start; | |
1286 | my $end; | |
1287 | ||
1288 | if ($timespan eq 'today') { | |
1289 | $start = $daystart; | |
1290 | $end = $start + 86400; | |
1291 | } elsif ($timespan eq 'yesterday') { | |
1292 | $end = $daystart; | |
1293 | $start = $end - 86400; | |
1294 | } elsif ($timespan eq 'week') { | |
1295 | $end = $daystart; | |
1296 | $start = $end - 7*86400; | |
1297 | } else { | |
1298 | die "internal error"; | |
1299 | } | |
1300 | ||
1301 | return ($start, $end); | |
1302 | } | |
1303 | ||
17a7c6c9 DM |
1304 | my $rbl_scan_last_cursor; |
1305 | my $rbl_scan_start_time = time(); | |
1306 | ||
1307 | sub scan_journal_for_rbl_rejects { | |
1308 | ||
1309 | # example postscreen log entry for RBL rejects | |
1310 | # Aug 29 08:00:36 proxmox postfix/postscreen[11266]: NOQUEUE: reject: RCPT from [x.x.x.x]:1234: 550 5.7.1 Service unavailable; client [x.x.x.x] blocked using zen.spamhaus.org; from=<xxxx>, to=<yyyy>, proto=ESMTP, helo=<zzz> | |
1311 | ||
2e0e3415 DM |
1312 | # example for PREGREET reject |
1313 | # Dec 7 06:57:11 proxmox postfix/postscreen[32084]: PREGREET 14 after 0.23 from [x.x.x.x]:63492: EHLO yyyyy\r\n | |
1314 | ||
17a7c6c9 DM |
1315 | my $identifier = 'postfix/postscreen'; |
1316 | ||
2e0e3415 DM |
1317 | my $rbl_count = 0; |
1318 | my $pregreet_count = 0; | |
17a7c6c9 DM |
1319 | |
1320 | my $parser = sub { | |
16ad0786 | 1321 | my $log = decode_json(shift); |
17a7c6c9 | 1322 | |
71edb4d0 FG |
1323 | $rbl_scan_last_cursor = $log->{__CURSOR} if defined($log->{__CURSOR}); |
1324 | ||
16ad0786 | 1325 | my $message = $log->{MESSAGE}; |
71edb4d0 FG |
1326 | return if !defined($message); |
1327 | ||
16ad0786 | 1328 | if ($message =~ m/^NOQUEUE:\sreject:.*550 5.7.1 Service unavailable/) { |
2e0e3415 | 1329 | $rbl_count++; |
16ad0786 | 1330 | } elsif ($message =~ m/^PREGREET\s\d+\safter\s/) { |
2e0e3415 DM |
1331 | $pregreet_count++; |
1332 | } | |
17a7c6c9 DM |
1333 | }; |
1334 | ||
1335 | # limit to last 5000 lines to avoid long delays | |
16ad0786 SI |
1336 | my $cmd = ['journalctl', '-o', 'json', '--output-fields', '__CURSOR,MESSAGE', |
1337 | '--no-pager', '--identifier', $identifier, '-n', 5000]; | |
17a7c6c9 DM |
1338 | |
1339 | if (defined($rbl_scan_last_cursor)) { | |
1340 | push @$cmd, "--after-cursor=${rbl_scan_last_cursor}"; | |
1341 | } else { | |
1342 | push @$cmd, "--since=@" . $rbl_scan_start_time; | |
1343 | } | |
1344 | ||
1345 | PVE::Tools::run_command($cmd, outfunc => $parser); | |
1346 | ||
2e0e3415 | 1347 | return ($rbl_count, $pregreet_count); |
17a7c6c9 DM |
1348 | } |
1349 | ||
5d5af7c5 DM |
1350 | my $hwaddress; |
1351 | ||
1352 | sub get_hwaddress { | |
1353 | ||
1354 | return $hwaddress if defined ($hwaddress); | |
1355 | ||
1356 | my $fn = '/etc/ssh/ssh_host_rsa_key.pub'; | |
1357 | my $sshkey = PVE::Tools::file_get_contents($fn); | |
1358 | $hwaddress = uc(Digest::MD5::md5_hex($sshkey)); | |
1359 | ||
1360 | return $hwaddress; | |
1361 | } | |
1362 | ||
75ce5866 DM |
1363 | my $default_locale = "en_US.UTF-8 UTF-8"; |
1364 | ||
1365 | sub cond_add_default_locale { | |
1366 | ||
1367 | my $filename = "/etc/locale.gen"; | |
1368 | ||
1369 | open(my $infh, "<", $filename) || return; | |
1370 | ||
1371 | while (defined(my $line = <$infh>)) { | |
1372 | if ($line =~ m/^\Q${default_locale}\E/) { | |
1373 | # already configured | |
1374 | return; | |
1375 | } | |
1376 | } | |
1377 | ||
1378 | seek($infh, 0, 0) // return; # seek failed | |
1379 | ||
1380 | open(my $outfh, ">", "$filename.tmp") || return; | |
1381 | ||
1382 | my $done; | |
1383 | while (defined(my $line = <$infh>)) { | |
1384 | if ($line =~ m/^#\s*\Q${default_locale}\E.*/) { | |
1385 | print $outfh "${default_locale}\n" if !$done; | |
1386 | $done = 1; | |
1387 | } else { | |
1388 | print $outfh $line; | |
1389 | } | |
1390 | } | |
1391 | ||
1392 | print STDERR "generation pmg default locale\n"; | |
1393 | ||
1394 | rename("$filename.tmp", $filename) || return; # rename failed | |
1395 | ||
1396 | system("dpkg-reconfigure locales -f noninteractive"); | |
1397 | } | |
1398 | ||
6529020a SI |
1399 | sub postgres_admin_cmd { |
1400 | my ($cmd, $options, @params) = @_; | |
1401 | ||
1402 | $cmd = ref($cmd) ? $cmd : [ $cmd ]; | |
1403 | ||
1404 | my $save_uid = POSIX::getuid(); | |
1405 | my $pg_uid = getpwnam('postgres') || die "getpwnam postgres failed\n"; | |
1406 | ||
98ea163e TL |
1407 | # cd to / to prevent warnings on EPERM (e.g. when running in /root) |
1408 | my $cwd = getcwd() || die "getcwd failed - $!\n"; | |
2808da9f | 1409 | ($cwd) = ($cwd =~ m|^(/.*)$|); #untaint |
98ea163e | 1410 | chdir('/') || die "could not chdir to '/' - $!\n"; |
6529020a SI |
1411 | PVE::Tools::setresuid(-1, $pg_uid, -1) || |
1412 | die "setresuid postgres ($pg_uid) failed - $!\n"; | |
1413 | ||
1414 | PVE::Tools::run_command([@$cmd, '-U', 'postgres', @params], %$options); | |
1415 | ||
1416 | PVE::Tools::setresuid(-1, $save_uid, -1) || | |
1417 | die "setresuid back failed - $!\n"; | |
2808da9f | 1418 | |
98ea163e | 1419 | chdir("$cwd") || die "could not chdir back to old working dir ($cwd) - $!\n"; |
6529020a SI |
1420 | } |
1421 | ||
8ba63317 SI |
1422 | sub get_pg_server_version { |
1423 | my $major_ver; | |
1424 | my $parser = sub { | |
1425 | my $line = shift; | |
1426 | # example output: | |
1427 | # 9.6.13 | |
1428 | # 11.4 (Debian 11.4-1) | |
1429 | # see https://www.postgresql.org/support/versioning/ | |
1430 | my ($first_comp) = ($line =~ m/^\s*([0-9]+)/); | |
1431 | if ($first_comp < 10) { | |
1432 | ($major_ver) = ($line =~ m/^([0-9]+\.[0-9]+)\.[0-9]+/); | |
1433 | } else { | |
1434 | $major_ver = $first_comp; | |
1435 | } | |
1436 | ||
1437 | }; | |
1438 | eval { | |
1439 | postgres_admin_cmd('psql', { outfunc => $parser }, '--quiet', | |
1440 | '--tuples-only', '--no-align', '--command', 'show server_version;'); | |
1441 | }; | |
1442 | ||
1443 | die "Unable to determine currently running Postgresql server version\n" | |
1444 | if ($@ || !defined($major_ver)); | |
1445 | ||
1446 | return $major_ver; | |
1447 | } | |
1448 | ||
592f4b80 SI |
1449 | sub reload_smtp_filter { |
1450 | ||
1451 | my $pid_file = '/run/pmg-smtp-filter.pid'; | |
1452 | my $pid = PVE::Tools::file_read_firstline($pid_file); | |
1453 | ||
1454 | return 0 if !$pid; | |
1455 | ||
1456 | return 0 if $pid !~ m/^(\d+)$/; | |
1457 | $pid = $1; # untaint | |
1458 | ||
1459 | return kill (10, $pid); # send SIGUSR1 | |
1460 | } | |
1461 | ||
567516ae DC |
1462 | sub domain_regex { |
1463 | my ($domains) = @_; | |
1464 | ||
1465 | my @ra; | |
1466 | foreach my $d (@$domains) { | |
1467 | # skip domains with non-DNS name characters | |
1468 | next if $d =~ m/[^A-Za-z0-9\-\.]/; | |
1469 | if ($d =~ m/^\.(.*)$/) { | |
1470 | my $dom = $1; | |
1471 | $dom =~ s/\./\\\./g; | |
1472 | push @ra, $dom; | |
1473 | push @ra, "\.\*\\.$dom"; | |
1474 | } else { | |
1475 | $d =~ s/\./\\\./g; | |
1476 | push @ra, $d; | |
1477 | } | |
1478 | } | |
1479 | ||
1480 | my $re = join ('|', @ra); | |
1481 | ||
1482 | my $regex = qr/\@($re)$/i; | |
1483 | ||
1484 | return $regex; | |
1485 | } | |
1486 | ||
d362c98d SI |
1487 | sub read_sa_channel { |
1488 | my ($filename) = @_; | |
1489 | ||
1490 | my $content = PVE::Tools::file_get_contents($filename); | |
1491 | my $channel = { | |
1492 | filename => $filename, | |
1493 | }; | |
1494 | ||
1495 | ($channel->{keyid}) = ($content =~ /^KEYID=([a-fA-F0-9]+)$/m); | |
1496 | die "no KEYID in $filename!\n" if !defined($channel->{keyid}); | |
1497 | ($channel->{channelurl}) = ($content =~ /^CHANNELURL=(.+)$/m); | |
1498 | die "no CHANNELURL in $filename!\n" if !defined($channel->{channelurl}); | |
1499 | ($channel->{gpgkey}) = ($content =~ /(?:^|\n)(-----BEGIN PGP PUBLIC KEY BLOCK-----.+-----END PGP PUBLIC KEY BLOCK-----)(?:\n|$)/s); | |
1500 | die "no GPG public key in $filename!\n" if !defined($channel->{gpgkey}); | |
1501 | ||
1502 | return $channel; | |
1503 | }; | |
1504 | ||
1505 | sub local_spamassassin_channels { | |
1506 | ||
1507 | my $res = []; | |
1508 | ||
1509 | my $local_channel_dir = '/etc/mail/spamassassin/channel.d/'; | |
1510 | ||
1511 | PVE::Tools::dir_glob_foreach($local_channel_dir, '.*\.conf', sub { | |
1512 | my ($filename) = @_; | |
1513 | my $channel = read_sa_channel($local_channel_dir.$filename); | |
1514 | push(@$res, $channel); | |
1515 | }); | |
1516 | ||
1517 | return $res; | |
1518 | } | |
567516ae | 1519 | |
98fd3ab0 SI |
1520 | sub update_local_spamassassin_channels { |
1521 | my ($verbose) = @_; | |
1522 | # import all configured channel's gpg-keys to sa-update's keyring | |
1523 | my $localchannels = PMG::Utils::local_spamassassin_channels(); | |
1524 | for my $channel (@$localchannels) { | |
1525 | my $importcmd = ['sa-update', '--import', $channel->{filename}]; | |
1526 | push @$importcmd, '-v' if $verbose; | |
1527 | ||
1528 | print "Importing gpg key from $channel->{filename}\n" if $verbose; | |
1529 | PVE::Tools::run_command($importcmd); | |
1530 | } | |
1531 | ||
1532 | my $fresh_updates = 0; | |
1533 | ||
1534 | for my $channel (@$localchannels) { | |
1535 | my $cmd = ['sa-update', '--channel', $channel->{channelurl}, '--gpgkey', $channel->{keyid}]; | |
1536 | push @$cmd, '-v' if $verbose; | |
1537 | ||
1538 | print "Updating $channel->{channelurl}\n" if $verbose; | |
1539 | my $ret = PVE::Tools::run_command($cmd, noerr => 1); | |
1540 | die "updating $channel->{channelurl} failed - sa-update exited with $ret\n" if $ret >= 2; | |
1541 | ||
1542 | $fresh_updates = 1 if $ret == 0; | |
1543 | } | |
1544 | ||
1545 | return $fresh_updates | |
1546 | } | |
1547 | ||
736b986f DC |
1548 | sub get_existing_object_id { |
1549 | my ($dbh, $obj_id, $obj_type, $value) = @_; | |
1550 | ||
1551 | my $sth = $dbh->prepare("SELECT id FROM Object WHERE ". | |
1552 | "Objectgroup_ID = ? AND ". | |
1553 | "ObjectType = ? AND ". | |
1554 | "Value = ?" | |
1555 | ); | |
1556 | $sth->execute($obj_id, $obj_type, $value); | |
1557 | ||
1558 | if (my $ref = $sth->fetchrow_hashref()) { | |
1559 | return $ref->{id}; | |
1560 | } | |
1561 | ||
1562 | return; | |
1563 | } | |
1564 | ||
15fcd85c SI |
1565 | sub try_decode_utf8 { |
1566 | my ($data) = @_; | |
1567 | return eval { decode('UTF-8', $data, 1) } // $data; | |
1568 | } | |
1569 | ||
758c7b6b | 1570 | 1; |