10 use POSIX
qw(strftime);
16 use Time
::HiRes qw
(gettimeofday
);
49 my $valid_pmg_realms = ['pam', 'pmg', 'quarantine'];
51 PVE
::JSONSchema
::register_standard_option
('realm', {
52 description
=> "Authentication domain ID",
54 enum
=> $valid_pmg_realms,
58 PVE
::JSONSchema
::register_standard_option
('pmg-starttime', {
59 description
=> "Only consider entries newer than 'starttime' (unix epoch). Default is 'now - 1day'.",
65 PVE
::JSONSchema
::register_standard_option
('pmg-endtime', {
66 description
=> "Only consider entries older than 'endtime' (unix epoch). This is set to '<start> + 1day' by default.",
72 PVE
::JSONSchema
::register_format
('pmg-userid', \
&verify_username
);
74 my ($username, $noerr) = @_;
76 $username = '' if !$username;
77 my $len = length($username);
79 die "user name '$username' is too short\n" if !$noerr;
83 die "user name '$username' is too long ($len > 64)\n" if !$noerr;
87 # we only allow a limited set of characters
88 # colon is not allowed, because we store usernames in
89 # colon separated lists)!
90 # slash is not allowed because it is used as pve API delimiter
91 # also see "man useradd"
92 my $realm_list = join('|', @$valid_pmg_realms);
93 if ($username =~ m!^([^\s:/]+)\@(${realm_list})$!) {
94 return wantarray ?
($username, $1, $2) : $username;
97 die "value '$username' does not look like a valid user name\n" if !$noerr;
102 PVE
::JSONSchema
::register_standard_option
('userid', {
103 description
=> "User ID",
104 type
=> 'string', format
=> 'pmg-userid',
109 PVE
::JSONSchema
::register_standard_option
('username', {
110 description
=> "Username (without realm)",
112 pattern
=> '[^\s:\/\@]{3,60}',
117 PVE
::JSONSchema
::register_standard_option
('pmg-email-address', {
118 description
=> "Email Address (allow most characters).",
120 pattern
=> '(?:[^\s\\\@]+\@[^\s\/\\\@]+)',
125 PVE
::JSONSchema
::register_standard_option
('pmg-whiteblacklist-entry-list', {
126 description
=> "White/Blacklist entry list (allow most characters). Can contain globs",
128 pattern
=> '(?:[^\s\/\\\;\,]+)(?:\,[^\s\/\\\;\,]+)*',
133 my ($dbh, $seq) = @_;
135 return $dbh->last_insert_id(
136 undef, undef, undef, undef, { sequence
=> $seq});
139 # quote all regex operators
143 $val =~ s/([\(\)\[\]\/\}\+\*\?\.\|\^\$\\])/\\$1/g;
148 sub file_older_than
{
149 my ($filename, $lasttime) = @_;
151 my $st = stat($filename);
153 return 0 if !defined($st);
155 return ($lasttime >= $st->ctime);
158 sub extract_filename
{
161 if (my $value = $head->recommended_filename()) {
163 if (my $decvalue = MIME
::Words
::decode_mimewords
($value)) {
164 $decvalue =~ s/\0/ /g;
165 $decvalue = PVE
::Tools
::trim
($decvalue);
174 my ($entity, $add_id) = @_;
178 PMG
::MIMEUtils
::traverse_mime_parts
($entity, sub {
180 foreach my $tag (grep {/^x-proxmox-tmp/i} $part->head->tags) {
181 $part->head->delete($tag);
184 $part->head->replace('X-Proxmox-tmp-AID', $id) if $add_id;
191 my ($body, $dh) = @_;
195 foreach my $k (keys %$dh) {
198 $body =~ s/__\Q${k}\E__/$v/gs;
206 my ($entity, $sender, $targets, $xforward, $me, $nodsn) = @_;
214 my $smtp = Net
::SMTP-
>new('::FFFF:127.0.0.1', Port
=> 10025, Hello
=> $me) ||
215 die "unable to connect to localhost at port 10025";
217 if (defined($xforward)) {
220 foreach my $attr (keys %{$xforward}) {
221 $xfwd .= " $attr=$xforward->{$attr}";
224 if ($xfwd && $smtp->command("XFORWARD", $xfwd)->response() != CMD_OK
) {
225 syslog
('err', "xforward error - got: %s %s", $smtp->code, scalar($smtp->message));
229 my $has_utf8_targets = 0;
230 foreach my $target (@$targets) {
231 if (utf8
::is_utf8
($target)) {
232 $has_utf8_targets = 1;
237 my $mail_opts = " BODY=8BITMIME";
239 if (utf8
::is_utf8
($sender)) {
240 $sender_addr = encode
('UTF-8', $smtp->_addr($sender));
241 $mail_opts .= " SMTPUTF8";
243 $sender_addr = $smtp->_addr($sender);
244 $mail_opts .= " SMTPUTF8" if $has_utf8_targets;
247 if (!$smtp->_MAIL("FROM:" . $sender_addr . $mail_opts)) {
248 syslog
('err', "smtp error - got: %s %s", $smtp->code, scalar ($smtp->message));
249 die "smtp from: ERROR";
252 my $rcpt_opts = $nodsn ?
" NOTIFY=NEVER" : "";
254 foreach my $target (@$targets) {
256 if (utf8
::is_utf8
($target)) {
257 $rcpt_addr = encode
('UTF-8', $smtp->_addr($target));
259 $rcpt_addr = $smtp->_addr($target);
261 if (!$smtp->_RCPT("TO:" . $rcpt_addr . $rcpt_opts)) {
262 syslog
('err', "smtp error - got: %s %s", $smtp->code, scalar($smtp->message));
263 die "smtp to: ERROR";
268 #$entity->sync_headers ();
271 my $out = PMG
::SMTPPrinter-
>new($smtp);
272 $entity->print($out);
274 # make sure we always have a newline at the end of the mail
275 # else dataend() fails
276 $smtp->datasend("\n");
278 if ($smtp->dataend()) {
279 my @msgs = $smtp->message;
280 $resmess = $msgs[$#msgs];
281 ($resid) = $resmess =~ m/Ok: queued as ([0-9A-Z]+)/;
282 $rescode = $smtp->code;
284 die sprintf("unexpected SMTP result - got: %s %s : WARNING", $smtp->code, $resmess);
287 my @msgs = $smtp->message;
288 $resmess = $msgs[$#msgs];
289 $rescode = $smtp->code;
290 die sprintf("sending data failed - got: %s %s : ERROR", $smtp->code, $resmess);
295 $smtp->quit if $smtp;
298 syslog
('err', $err);
301 return wantarray ?
($resid, $rescode, $resmess) : $resid;
304 sub analyze_custom_check
{
305 my ($queue, $dname, $pmg_cfg) = @_;
307 my $enable_custom_check = $pmg_cfg->get('admin', 'custom_check');
308 return undef if !$enable_custom_check;
311 my $customcheck_exe = $pmg_cfg->get('admin', 'custom_check_path');
312 my $customcheck_apiver = 'v1';
313 my ($csec, $usec) = gettimeofday
();
323 syslog
('err', $errmsg);
326 my $customcheck_output_apiver;
332 if ($line =~ /^v\d$/) {
333 die "api version already defined!\n" if defined($customcheck_output_apiver);
334 $customcheck_output_apiver = $line;
335 die "api version mismatch - expected $customcheck_apiver, got $customcheck_output_apiver !\n"
336 if ($customcheck_output_apiver ne $customcheck_apiver);
337 } elsif ($line =~ /^SCORE: (-?[0-9]+|.[0-9]+|[0-9]+.[0-9]+)$/) {
340 } elsif ($line =~ /^VIRUS: (.+)$/) {
343 } elsif ($line =~ /^OK$/) {
346 die "got unexpected output!\n";
348 die "got more than 1 result outputs\n" if ( $have_result && $result_flag);
349 $have_result = $result_flag;
352 PVE
::Tools
::run_command
([$customcheck_exe, $customcheck_apiver, $dname],
353 errmsg
=> "$queue->{logid} custom check error",
354 errfunc
=> $log_err, outfunc
=> $parser, timeout
=> $timeout);
356 die "no api version returned\n" if !defined($customcheck_output_apiver);
357 die "no result output!\n" if !$have_result;
362 syslog
('info', "$queue->{logid}: virus detected: $vinfo (custom)");
365 my ($csec_end, $usec_end) = gettimeofday
();
366 $queue->{ptime_custom
} =
367 int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
370 syslog
('err', $err);
372 $queue->{errors
} = 1;
375 $queue->{vinfo_custom
} = $vinfo;
376 $queue->{spam_custom
} = $spam_score;
378 return ($vinfo, $spam_score);
381 sub analyze_virus_clam
{
382 my ($queue, $dname, $pmg_cfg) = @_;
387 my $clamdscan_opts = "--stdout";
389 my ($csec, $usec) = gettimeofday
();
395 $previous_alarm = alarm($timeout);
398 die "$queue->{logid}: Maximum time ($timeout sec) exceeded. " .
399 "virus analyze (clamav) failed: ERROR";
402 open(CMD
, "/usr/bin/clamdscan $clamdscan_opts '$dname'|") ||
403 die "$queue->{logid}: can't exec clamdscan: $! : ERROR";
408 while (defined(my $line = <CMD
>)) {
409 if ($line =~ m/^$dname.*:\s+([^ :]*)\s+FOUND$/) {
410 # we just use the first detected virus name
411 $vinfo = $1 if !$vinfo;
412 } elsif ($line =~ m/^Infected files:\s(\d*)$/i) {
421 alarm(0); # avoid race conditions
423 if (!defined($ifiles)) {
424 die "$queue->{logid}: got undefined output from " .
425 "virus detector: $response : ERROR";
429 syslog
('info', "$queue->{logid}: virus detected: $vinfo (clamav)");
434 alarm($previous_alarm);
436 my ($csec_end, $usec_end) = gettimeofday
();
437 $queue->{ptime_clam
} =
438 int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
441 syslog
('err', $err);
443 $queue->{errors
} = 1;
446 $queue->{vinfo_clam
} = $vinfo;
448 return $vinfo ?
"$vinfo (clamav)" : undef;
451 sub analyze_virus_avast
{
452 my ($queue, $dname, $pmg_cfg) = @_;
457 my ($csec, $usec) = gettimeofday
();
463 $previous_alarm = alarm($timeout);
466 die "$queue->{logid}: Maximum time ($timeout sec) exceeded. " .
467 "virus analyze (avast) failed: ERROR";
470 open(my $cmd, '-|', 'scan', $dname) ||
471 die "$queue->{logid}: can't exec avast scan: $! : ERROR";
474 while (defined(my $line = <$cmd>)) {
475 if ($line =~ m/^$dname\s+(.*\S)\s*$/) {
476 # we just use the first detected virus name
477 $vinfo = $1 if !$vinfo;
485 alarm(0); # avoid race conditions
488 syslog
('info', "$queue->{logid}: virus detected: $vinfo (avast)");
493 alarm($previous_alarm);
495 my ($csec_end, $usec_end) = gettimeofday
();
496 $queue->{ptime_clam
} =
497 int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
500 syslog
('err', $err);
502 $queue->{errors
} = 1;
505 return undef if !$vinfo;
507 $queue->{vinfo_avast
} = $vinfo;
509 return "$vinfo (avast)";
513 my ($queue, $filename, $pmg_cfg, $testmode) = @_;
515 # TODO: support other virus scanners?
518 my $vinfo_clam = analyze_virus_clam
($queue, $filename, $pmg_cfg);
519 my $vinfo_avast = analyze_virus_avast
($queue, $filename, $pmg_cfg);
521 return $vinfo_avast || $vinfo_clam;
524 my $enable_avast = $pmg_cfg->get('admin', 'avast');
527 if (my $vinfo = analyze_virus_avast
($queue, $filename, $pmg_cfg)) {
532 my $enable_clamav = $pmg_cfg->get('admin', 'clamav');
534 if ($enable_clamav) {
535 if (my $vinfo = analyze_virus_clam
($queue, $filename, $pmg_cfg)) {
543 sub magic_mime_type_for_file
{
546 # we do not use get_mime_type_for_file, because that considers
547 # filename extensions - we only want magic type detection
549 my $bufsize = Xdgmime
::xdg_mime_get_max_buffer_extents
();
550 die "got strange value for max_buffer_extents" if $bufsize > 4096*10;
552 my $ct = "application/octet-stream";
554 my $fh = IO
::File-
>new("<$filename") ||
555 die "unable to open file '$filename' - $!";
558 if (($len = $fh->read($buf, $bufsize)) > 0) {
559 $ct = xdg_mime_get_mime_type_for_data
($buf, $len);
563 die "unable to read file '$filename' - $!" if ($len < 0);
571 if (my $path = $entity->{PMX_decoded_path
}) {
573 # set a reasonable default if magic does not give a result
574 $entity->{PMX_magic_ct
} = $entity->head->mime_attr('content-type');
576 if (my $ct = magic_mime_type_for_file
($path)) {
577 if ($ct ne 'application/octet-stream' || !$entity->{PMX_magic_ct
}) {
578 $entity->{PMX_magic_ct
} = $ct;
582 my $filename = $entity->head->recommended_filename;
583 $filename = basename
($path) if !defined($filename) || $filename eq '';
585 if (my $ct = xdg_mime_get_mime_type_from_file_name
($filename)) {
586 $entity->{PMX_glob_ct
} = $ct;
590 foreach my $part ($entity->parts) {
591 add_ct_marks
($part);
595 # x509 certificate utils
597 # only write output if something fails
603 my $record_output = sub {
609 PVE
::Tools
::run_command
($cmd, outfunc
=> $record_output,
610 errfunc
=> $record_output);
615 print STDERR
$outbuf;
620 my $proxmox_tls_cert_fn = "/etc/pmg/pmg-tls.pem";
622 sub gen_proxmox_tls_cert
{
625 my $resolv = PVE
::INotify
::read_file
('resolvconf');
626 my $domain = $resolv->{search
};
628 my $company = $domain; # what else ?
629 my $cn = "*.$domain";
631 return if !$force && -f
$proxmox_tls_cert_fn;
633 my $sslconf = <<__EOD__;
634 RANDFILE = /root/.rnd
639 distinguished_name = req_distinguished_name
640 req_extensions = v3_req
642 string_mask = nombstr
644 [ req_distinguished_name ]
645 organizationalUnitName = Proxmox Mail Gateway
646 organizationName = $company
650 basicConstraints = CA:FALSE
652 keyUsage = nonRepudiation, digitalSignature, keyEncipherment
655 my $cfgfn = "/tmp/pmgtlsconf-$$.tmp";
656 my $fh = IO
::File-
>new ($cfgfn, "w");
661 my $cmd = ['openssl', 'req', '-batch', '-x509', '-new', '-sha256',
662 '-config', $cfgfn, '-days', 3650, '-nodes',
663 '-out', $proxmox_tls_cert_fn,
664 '-keyout', $proxmox_tls_cert_fn];
665 run_silent_cmd
($cmd);
669 unlink $proxmox_tls_cert_fn;
671 die "unable to generate proxmox certificate request:\n$err";
677 sub find_local_network_for_ip
{
678 my ($ip, $noerr) = @_;
680 my $testip = Net
::IP-
>new($ip);
682 my $isv6 = $testip->version == 6;
684 PVE
::ProcFSTools
::read_proc_net_ipv6_route
() :
685 PVE
::ProcFSTools
::read_proc_net_route
();
687 foreach my $entry (@$routes) {
690 $mask = $entry->{prefix
};
691 next if !$mask; # skip the default route...
693 $mask = $PVE::Network
::ipv4_mask_hash_localnet-
>{$entry->{mask
}};
694 next if !defined($mask);
696 my $cidr = "$entry->{dest}/$mask";
697 my $testnet = Net
::IP-
>new($cidr);
698 my $overlap = $testnet->overlaps($testip);
699 if ($overlap == $Net::IP
::IP_B_IN_A_OVERLAP
||
700 $overlap == $Net::IP
::IP_IDENTICAL
)
706 return undef if $noerr;
708 die "unable to detect local network for ip '$ip'\n";
711 my $service_aliases = {
712 'postfix' => 'postfix@-',
713 'postgres' => 'postgresql@11-main',
716 sub lookup_real_service_name
{
719 return $service_aliases->{$alias} // $alias;
722 sub get_full_service_state
{
729 if ($line =~ m/^([^=\s]+)=(.*)$/) {
734 $service = $service_aliases->{$service} // $service;
735 PVE
::Tools
::run_command
(['systemctl', 'show', $service], outfunc
=> $parser);
740 our $db_service_list = [
741 'pmgpolicy', 'pmgmirror', 'pmgtunnel', 'pmg-smtp-filter' ];
743 sub service_wait_stopped
{
744 my ($timeout, $service_list) = @_;
746 my $starttime = time();
748 foreach my $service (@$service_list) {
749 PVE
::Tools
::run_command
(['systemctl', 'stop', $service]);
755 foreach my $service (@$service_list) {
756 my $ss = get_full_service_state
($service);
757 my $state = $ss->{ActiveState
} // 'unknown';
759 if ($state ne 'inactive') {
760 if ((time() - $starttime) > $timeout) {
761 syslog
('err', "unable to stop services (got timeout)");
776 my ($service, $cmd) = @_;
778 die "unknown service command '$cmd'\n"
779 if $cmd !~ m/^(start|stop|restart|reload|reload-or-restart)$/;
781 if ($service eq 'pmgdaemon' || $service eq 'pmgproxy') {
782 die "invalid service cmd '$service $cmd': ERROR" if $cmd eq 'stop';
783 } elsif ($service eq 'fetchmail') {
784 # use restart instead of start - else it does not start 'exited' unit
785 # after setting START_DAEMON=yes in /etc/default/fetchmail
786 $cmd = 'restart' if $cmd eq 'start';
789 $service = $service_aliases->{$service} // $service;
790 PVE
::Tools
::run_command
(['systemctl', $cmd, $service]);
796 # make sure the file exists (else postmap fails)
797 IO
::File-
>new($filename, 'a', 0644);
799 my $mtime_src = (CORE
::stat($filename))[9] //
800 die "unbale to read mtime of $filename\n";
802 my $mtime_dst = (CORE
::stat("$filename.db"))[9] // 0;
804 # if not changed, do nothing
805 return if $mtime_src <= $mtime_dst;
808 PVE
::Tools
::run_command
(
809 ['/usr/sbin/postmap', $filename],
810 errmsg
=> "unable to update postfix table $filename");
821 my $read_cvd_info = sub {
822 my ($dbname, $dbfile) = @_;
825 my $fh = IO
::File-
>new("<$dbfile");
827 warn "can't open ClamAV Database $dbname ($dbfile) - $!\n";
830 $fh->read($header, 512);
833 ## ClamAV-VDB:16 Mar 2016 23-17 +0000:57:4218790:60:06386f34a16ebeea2733ab037f0536be:
834 if ($header =~ m/^(ClamAV-VDB):([^:]+):(\d+):(\d+):/) {
835 my ($ftype, $btime, $version, $nsigs) = ($1, $2, $3, $4);
839 build_time
=> $btime,
844 warn "unable to parse ClamAV Database $dbname ($dbfile)\n";
849 my $filename = "/var/lib/clamav/main.inc/main.info";
850 $filename = "/var/lib/clamav/main.cvd" if ! -f
$filename;
852 $read_cvd_info->('main', $filename) if -f
$filename;
855 $filename = "/var/lib/clamav/daily.inc/daily.info";
856 $filename = "/var/lib/clamav/daily.cvd" if ! -f
$filename;
857 $filename = "/var/lib/clamav/daily.cld" if ! -f
$filename;
859 $read_cvd_info->('daily', $filename) if -f
$filename;
861 $filename = "/var/lib/clamav/bytecode.cvd";
862 $read_cvd_info->('bytecode', $filename) if -f
$filename;
864 my $ss_dbs_fn = "/var/lib/clamav-unofficial-sigs/configs/ss-include-dbs.txt";
865 my $ss_dbs_files = {};
866 if (my $ssfh = IO
::File-
>new("<${ss_dbs_fn}")) {
867 while (defined(my $line = <$ssfh>)) {
869 $ss_dbs_files->{$line} = 1;
874 foreach $filename (</var/lib
/clamav/*>) {
875 my $fn = basename
($filename);
876 next if !$ss_dbs_files->{$fn};
878 my $fh = IO
::File-
>new("<$filename");
879 next if !defined($fh);
882 my $mtime = $st->mtime();
883 $last = $mtime if $mtime > $last;
884 while (defined(my $line = <$fh>)) { $nsigs++; }
889 name
=> 'sanesecurity',
890 type
=> 'unofficial',
891 build_time
=> strftime
("%d %b %Y %H-%M %z", localtime($last)),
900 my $rrd_dir = "/var/lib/rrdcached/db";
901 my $rrdcached_socket = "/var/run/rrdcached.sock";
904 "DS:loadavg:GAUGE:120:0:U",
905 "DS:maxcpu:GAUGE:120:0:U",
906 "DS:cpu:GAUGE:120:0:U",
907 "DS:iowait:GAUGE:120:0:U",
908 "DS:memtotal:GAUGE:120:0:U",
909 "DS:memused:GAUGE:120:0:U",
910 "DS:swaptotal:GAUGE:120:0:U",
911 "DS:swapused:GAUGE:120:0:U",
912 "DS:roottotal:GAUGE:120:0:U",
913 "DS:rootused:GAUGE:120:0:U",
914 "DS:netin:DERIVE:120:0:U",
915 "DS:netout:DERIVE:120:0:U",
917 "RRA:AVERAGE:0.5:1:70", # 1 min avg - one hour
918 "RRA:AVERAGE:0.5:30:70", # 30 min avg - one day
919 "RRA:AVERAGE:0.5:180:70", # 3 hour avg - one week
920 "RRA:AVERAGE:0.5:720:70", # 12 hour avg - one month
921 "RRA:AVERAGE:0.5:10080:70", # 7 day avg - ony year
923 "RRA:MAX:0.5:1:70", # 1 min max - one hour
924 "RRA:MAX:0.5:30:70", # 30 min max - one day
925 "RRA:MAX:0.5:180:70", # 3 hour max - one week
926 "RRA:MAX:0.5:720:70", # 12 hour max - one month
927 "RRA:MAX:0.5:10080:70", # 7 day max - ony year
930 sub cond_create_rrd_file
{
931 my ($filename, $rrddef) = @_;
933 return if -f
$filename;
935 my @args = ($filename);
937 push @args, "--daemon" => "unix:${rrdcached_socket}"
938 if -S
$rrdcached_socket;
940 push @args, '--step', 60;
942 push @args, @$rrddef;
944 # print "TEST: " . join(' ', @args) . "\n";
947 my $err = RRDs
::error
;
948 die "RRD error: $err\n" if $err;
951 sub update_node_status_rrd
{
953 my $filename = "$rrd_dir/pmg-node-v1.rrd";
954 cond_create_rrd_file
($filename, $rrd_def_node);
956 my ($avg1, $avg5, $avg15) = PVE
::ProcFSTools
::read_loadavg
();
958 my $stat = PVE
::ProcFSTools
::read_proc_stat
();
960 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
962 my ($uptime) = PVE
::ProcFSTools
::read_proc_uptime
();
964 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
966 my $maxcpu = $cpuinfo->{cpus
};
968 # traffic from/to physical interface cards
971 foreach my $dev (keys %$netdev) {
972 next if $dev !~ m/^$PVE::Network::PHYSICAL_NIC_RE$/;
973 $netin += $netdev->{$dev}->{receive
};
974 $netout += $netdev->{$dev}->{transmit
};
977 my $meminfo = PVE
::ProcFSTools
::read_meminfo
();
979 my $dinfo = df
('/', 1); # output is bytes
983 # everything not free is considered to be used
984 my $dused = $dinfo->{blocks
} - $dinfo->{bfree
};
986 my $data = "$ctime:$avg1:$maxcpu:$stat->{cpu}:$stat->{wait}:" .
987 "$meminfo->{memtotal}:$meminfo->{memused}:" .
988 "$meminfo->{swaptotal}:$meminfo->{swapused}:" .
989 "$dinfo->{blocks}:$dused:$netin:$netout";
992 my @args = ($filename);
994 push @args, "--daemon" => "unix:${rrdcached_socket}"
995 if -S
$rrdcached_socket;
999 # print "TEST: " . join(' ', @args) . "\n";
1001 RRDs
::update
(@args);
1002 my $err = RRDs
::error
;
1003 die "RRD error: $err\n" if $err;
1006 sub create_rrd_data
{
1007 my ($rrdname, $timeframe, $cf) = @_;
1009 my $rrd = "${rrd_dir}/$rrdname";
1013 day
=> [ 60*30, 70 ],
1014 week
=> [ 60*180, 70 ],
1015 month
=> [ 60*720, 70 ],
1016 year
=> [ 60*10080, 70 ],
1019 my ($reso, $count) = @{$setup->{$timeframe}};
1020 my $ctime = $reso*int(time()/$reso);
1021 my $req_start = $ctime - $reso*$count;
1023 $cf = "AVERAGE" if !$cf;
1031 push @args, "--daemon" => "unix:${rrdcached_socket}"
1032 if -S
$rrdcached_socket;
1034 my ($start, $step, $names, $data) = RRDs
::fetch
($rrd, $cf, @args);
1036 my $err = RRDs
::error
;
1037 die "RRD error: $err\n" if $err;
1039 die "got wrong time resolution ($step != $reso)\n"
1043 my $fields = scalar(@$names);
1044 for my $line (@$data) {
1045 my $entry = { 'time' => $start };
1047 for (my $i = 0; $i < $fields; $i++) {
1048 my $name = $names->[$i];
1049 if (defined(my $val = $line->[$i])) {
1050 $entry->{$name} = $val;
1052 # leave empty fields undefined
1053 # maybe make this configurable?
1062 sub decode_to_html
{
1063 my ($charset, $data) = @_;
1067 eval { $res = encode_entities
(decode
($charset, $data)); };
1072 sub decode_rfc1522
{
1080 foreach my $r (MIME
::Words
::decode_mimewords
($enc)) {
1084 $res .= decode
($cs, $d);
1097 sub rfc1522_to_html
{
1105 foreach my $r (MIME
::Words
::decode_mimewords
($enc)) {
1109 $res .= encode_entities
(decode
($cs, $d));
1111 $res .= encode_entities
($d);
1122 # RFC 2047 B-ENCODING http://rfc.net/rfc2047.html
1123 # (Q-Encoding is complex and error prone)
1124 sub bencode_header
{
1127 my $CRLF = "\015\012";
1129 # Nonprintables (controls + x7F + 8bit):
1130 my $NONPRINT = "\\x00-\\x1F\\x7F-\\xFF";
1132 # always use utf-8 (work with japanese character sets)
1133 $txt = encode
("UTF-8", $txt);
1135 return $txt if $txt !~ /[$NONPRINT]/o;
1139 while ($txt =~ s/^(.{1,42})//sm) {
1140 my $t = MIME
::Words
::encode_mimeword
($1, 'B', 'UTF-8');
1141 $res .= $res ?
"\015\012\t$t" : $t;
1147 sub load_sa_descriptions
{
1148 my ($additional_dirs) = @_;
1150 my @dirs = ('/usr/share/spamassassin',
1151 '/usr/share/spamassassin-extra');
1153 push @dirs, @$additional_dirs if @$additional_dirs;
1157 my $parse_sa_file = sub {
1160 open(my $fh,'<', $file);
1161 return if !defined($fh);
1163 while (defined(my $line = <$fh>)) {
1164 if ($line =~ m/^(?:\s*)describe\s+(\S+)\s+(.*)\s*$/) {
1165 my ($name, $desc) = ($1, $2);
1166 next if $res->{$name};
1167 $res->{$name}->{desc
} = $desc;
1168 if ($desc =~ m
|[\
(\s
](http
:\
/\/\S
+\
.[^\s\
.\
)]+\
.[^\s\
.\
)]+)|i
) {
1169 $res->{$name}->{url
} = $1;
1176 foreach my $dir (@dirs) {
1177 foreach my $file (<$dir/*.cf
>) {
1178 $parse_sa_file->($file);
1182 $res->{'ClamAVHeuristics'}->{desc
} = "ClamAV heuristic tests";
1190 my $days = int($uptime/86400);
1191 $uptime -= $days*86400;
1193 my $hours = int($uptime/3600);
1194 $uptime -= $hours*3600;
1196 my $mins = $uptime/60;
1199 my $ds = $days > 1 ?
'days' : 'day';
1200 return sprintf "%d $ds %02d:%02d", $days, $hours, $mins;
1202 return sprintf "%02d:%02d", $hours, $mins;
1206 sub finalize_report
{
1207 my ($tt, $template, $data, $mailfrom, $receiver, $debug) = @_;
1211 $tt->process($template, $data, \
$html) ||
1212 die $tt->error() . "\n";
1215 if ($html =~ m
|^\s
*<title
>(.*)</title
>|m
) {
1218 die "unable to extract template title\n";
1221 my $top = MIME
::Entity-
>build(
1222 Type
=> "multipart/related",
1223 To
=> $data->{pmail
},
1225 Subject
=> bencode_header
(decode_entities
($title)));
1229 Type
=> "text/html",
1230 Encoding
=> $debug ?
'binary' : 'quoted-printable');
1236 # we use an empty envelope sender (we don't want to receive NDRs)
1237 PMG
::Utils
::reinject_mail
($top, '', [$receiver], undef, $data->{fqdn
});
1240 sub lookup_timespan
{
1241 my ($timespan) = @_;
1243 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
1244 my $daystart = timelocal
(0, 0, 0, $mday, $mon, $year);
1249 if ($timespan eq 'today') {
1251 $end = $start + 86400;
1252 } elsif ($timespan eq 'yesterday') {
1254 $start = $end - 86400;
1255 } elsif ($timespan eq 'week') {
1257 $start = $end - 7*86400;
1259 die "internal error";
1262 return ($start, $end);
1265 my $rbl_scan_last_cursor;
1266 my $rbl_scan_start_time = time();
1268 sub scan_journal_for_rbl_rejects
{
1270 # example postscreen log entry for RBL rejects
1271 # 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>
1273 # example for PREGREET reject
1274 # Dec 7 06:57:11 proxmox postfix/postscreen[32084]: PREGREET 14 after 0.23 from [x.x.x.x]:63492: EHLO yyyyy\r\n
1276 my $identifier = 'postfix/postscreen';
1279 my $pregreet_count = 0;
1282 my $log = decode_json
(shift);
1284 $rbl_scan_last_cursor = $log->{__CURSOR
} if defined($log->{__CURSOR
});
1286 my $message = $log->{MESSAGE
};
1287 return if !defined($message);
1289 if ($message =~ m/^NOQUEUE:\sreject:.*550 5.7.1 Service unavailable/) {
1291 } elsif ($message =~ m/^PREGREET\s\d+\safter\s/) {
1296 # limit to last 5000 lines to avoid long delays
1297 my $cmd = ['journalctl', '-o', 'json', '--output-fields', '__CURSOR,MESSAGE',
1298 '--no-pager', '--identifier', $identifier, '-n', 5000];
1300 if (defined($rbl_scan_last_cursor)) {
1301 push @$cmd, "--after-cursor=${rbl_scan_last_cursor}";
1303 push @$cmd, "--since=@" . $rbl_scan_start_time;
1306 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1308 return ($rbl_count, $pregreet_count);
1315 return $hwaddress if defined ($hwaddress);
1317 my $fn = '/etc/ssh/ssh_host_rsa_key.pub';
1318 my $sshkey = PVE
::Tools
::file_get_contents
($fn);
1319 $hwaddress = uc(Digest
::MD5
::md5_hex
($sshkey));
1324 my $default_locale = "en_US.UTF-8 UTF-8";
1326 sub cond_add_default_locale
{
1328 my $filename = "/etc/locale.gen";
1330 open(my $infh, "<", $filename) || return;
1332 while (defined(my $line = <$infh>)) {
1333 if ($line =~ m/^\Q${default_locale}\E/) {
1334 # already configured
1339 seek($infh, 0, 0) // return; # seek failed
1341 open(my $outfh, ">", "$filename.tmp") || return;
1344 while (defined(my $line = <$infh>)) {
1345 if ($line =~ m/^#\s*\Q${default_locale}\E.*/) {
1346 print $outfh "${default_locale}\n" if !$done;
1353 print STDERR
"generation pmg default locale\n";
1355 rename("$filename.tmp", $filename) || return; # rename failed
1357 system("dpkg-reconfigure locales -f noninteractive");
1360 sub postgres_admin_cmd
{
1361 my ($cmd, $options, @params) = @_;
1363 $cmd = ref($cmd) ?
$cmd : [ $cmd ];
1365 my $save_uid = POSIX
::getuid
();
1366 my $pg_uid = getpwnam('postgres') || die "getpwnam postgres failed\n";
1368 PVE
::Tools
::setresuid
(-1, $pg_uid, -1) ||
1369 die "setresuid postgres ($pg_uid) failed - $!\n";
1371 PVE
::Tools
::run_command
([@$cmd, '-U', 'postgres', @params], %$options);
1373 PVE
::Tools
::setresuid
(-1, $save_uid, -1) ||
1374 die "setresuid back failed - $!\n";
1377 sub get_pg_server_version
{
1383 # 11.4 (Debian 11.4-1)
1384 # see https://www.postgresql.org/support/versioning/
1385 my ($first_comp) = ($line =~ m/^\s*([0-9]+)/);
1386 if ($first_comp < 10) {
1387 ($major_ver) = ($line =~ m/^([0-9]+\.[0-9]+)\.[0-9]+/);
1389 $major_ver = $first_comp;
1394 postgres_admin_cmd
('psql', { outfunc
=> $parser }, '--quiet',
1395 '--tuples-only', '--no-align', '--command', 'show server_version;');
1398 die "Unable to determine currently running Postgresql server version\n"
1399 if ($@ || !defined($major_ver));
1404 sub reload_smtp_filter
{
1406 my $pid_file = '/run/pmg-smtp-filter.pid';
1407 my $pid = PVE
::Tools
::file_read_firstline
($pid_file);
1411 return 0 if $pid !~ m/^(\d+)$/;
1412 $pid = $1; # untaint
1414 return kill (10, $pid); # send SIGUSR1
1421 foreach my $d (@$domains) {
1422 # skip domains with non-DNS name characters
1423 next if $d =~ m/[^A-Za-z0-9\-\.]/;
1424 if ($d =~ m/^\.(.*)$/) {
1426 $dom =~ s/\./\\\./g;
1428 push @ra, "\.\*\\.$dom";
1435 my $re = join ('|', @ra);
1437 my $regex = qr/\@($re)$/i;
1442 sub read_sa_channel
{
1443 my ($filename) = @_;
1445 my $content = PVE
::Tools
::file_get_contents
($filename);
1447 filename
=> $filename,
1450 ($channel->{keyid
}) = ($content =~ /^KEYID=([a-fA-F0-9]+)$/m);
1451 die "no KEYID in $filename!\n" if !defined($channel->{keyid
});
1452 ($channel->{channelurl
}) = ($content =~ /^CHANNELURL=(.+)$/m);
1453 die "no CHANNELURL in $filename!\n" if !defined($channel->{channelurl
});
1454 ($channel->{gpgkey
}) = ($content =~ /(?:^|\n)(-----BEGIN PGP PUBLIC KEY BLOCK-----.+-----END PGP PUBLIC KEY BLOCK-----)(?:\n|$)/s);
1455 die "no GPG public key in $filename!\n" if !defined($channel->{gpgkey
});
1460 sub local_spamassassin_channels
{
1464 my $local_channel_dir = '/etc/mail/spamassassin/channel.d/';
1466 PVE
::Tools
::dir_glob_foreach
($local_channel_dir, '.*\.conf', sub {
1467 my ($filename) = @_;
1468 my $channel = read_sa_channel
($local_channel_dir.$filename);
1469 push(@$res, $channel);
1475 sub update_local_spamassassin_channels
{
1477 # import all configured channel's gpg-keys to sa-update's keyring
1478 my $localchannels = PMG
::Utils
::local_spamassassin_channels
();
1479 for my $channel (@$localchannels) {
1480 my $importcmd = ['sa-update', '--import', $channel->{filename
}];
1481 push @$importcmd, '-v' if $verbose;
1483 print "Importing gpg key from $channel->{filename}\n" if $verbose;
1484 PVE
::Tools
::run_command
($importcmd);
1487 my $fresh_updates = 0;
1489 for my $channel (@$localchannels) {
1490 my $cmd = ['sa-update', '--channel', $channel->{channelurl
}, '--gpgkey', $channel->{keyid
}];
1491 push @$cmd, '-v' if $verbose;
1493 print "Updating $channel->{channelurl}\n" if $verbose;
1494 my $ret = PVE
::Tools
::run_command
($cmd, noerr
=> 1);
1495 die "updating $channel->{channelurl} failed - sa-update exited with $ret\n" if $ret >= 2;
1497 $fresh_updates = 1 if $ret == 0;
1500 return $fresh_updates