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@-',
715 sub lookup_real_service_name
{
718 if ($alias eq 'postgres') {
719 my $pg_ver = get_pg_server_version
();
720 return "postgresl\@${pg_ver}-main";
723 return $service_aliases->{$alias} // $alias;
726 sub get_full_service_state
{
733 if ($line =~ m/^([^=\s]+)=(.*)$/) {
738 $service = $service_aliases->{$service} // $service;
739 PVE
::Tools
::run_command
(['systemctl', 'show', $service], outfunc
=> $parser);
744 our $db_service_list = [
745 'pmgpolicy', 'pmgmirror', 'pmgtunnel', 'pmg-smtp-filter' ];
747 sub service_wait_stopped
{
748 my ($timeout, $service_list) = @_;
750 my $starttime = time();
752 foreach my $service (@$service_list) {
753 PVE
::Tools
::run_command
(['systemctl', 'stop', $service]);
759 foreach my $service (@$service_list) {
760 my $ss = get_full_service_state
($service);
761 my $state = $ss->{ActiveState
} // 'unknown';
763 if ($state ne 'inactive') {
764 if ((time() - $starttime) > $timeout) {
765 syslog
('err', "unable to stop services (got timeout)");
780 my ($service, $cmd) = @_;
782 die "unknown service command '$cmd'\n"
783 if $cmd !~ m/^(start|stop|restart|reload|reload-or-restart)$/;
785 if ($service eq 'pmgdaemon' || $service eq 'pmgproxy') {
786 die "invalid service cmd '$service $cmd': ERROR" if $cmd eq 'stop';
787 } elsif ($service eq 'fetchmail') {
788 # use restart instead of start - else it does not start 'exited' unit
789 # after setting START_DAEMON=yes in /etc/default/fetchmail
790 $cmd = 'restart' if $cmd eq 'start';
793 $service = $service_aliases->{$service} // $service;
794 PVE
::Tools
::run_command
(['systemctl', $cmd, $service]);
800 # make sure the file exists (else postmap fails)
801 IO
::File-
>new($filename, 'a', 0644);
803 my $mtime_src = (CORE
::stat($filename))[9] //
804 die "unbale to read mtime of $filename\n";
806 my $mtime_dst = (CORE
::stat("$filename.db"))[9] // 0;
808 # if not changed, do nothing
809 return if $mtime_src <= $mtime_dst;
812 PVE
::Tools
::run_command
(
813 ['/usr/sbin/postmap', $filename],
814 errmsg
=> "unable to update postfix table $filename");
825 my $read_cvd_info = sub {
826 my ($dbname, $dbfile) = @_;
829 my $fh = IO
::File-
>new("<$dbfile");
831 warn "can't open ClamAV Database $dbname ($dbfile) - $!\n";
834 $fh->read($header, 512);
837 ## ClamAV-VDB:16 Mar 2016 23-17 +0000:57:4218790:60:06386f34a16ebeea2733ab037f0536be:
838 if ($header =~ m/^(ClamAV-VDB):([^:]+):(\d+):(\d+):/) {
839 my ($ftype, $btime, $version, $nsigs) = ($1, $2, $3, $4);
843 build_time
=> $btime,
848 warn "unable to parse ClamAV Database $dbname ($dbfile)\n";
853 my $filename = "/var/lib/clamav/main.inc/main.info";
854 $filename = "/var/lib/clamav/main.cvd" if ! -f
$filename;
856 $read_cvd_info->('main', $filename) if -f
$filename;
859 $filename = "/var/lib/clamav/daily.inc/daily.info";
860 $filename = "/var/lib/clamav/daily.cvd" if ! -f
$filename;
861 $filename = "/var/lib/clamav/daily.cld" if ! -f
$filename;
863 $read_cvd_info->('daily', $filename) if -f
$filename;
865 $filename = "/var/lib/clamav/bytecode.cvd";
866 $read_cvd_info->('bytecode', $filename) if -f
$filename;
868 my $ss_dbs_fn = "/var/lib/clamav-unofficial-sigs/configs/ss-include-dbs.txt";
869 my $ss_dbs_files = {};
870 if (my $ssfh = IO
::File-
>new("<${ss_dbs_fn}")) {
871 while (defined(my $line = <$ssfh>)) {
873 $ss_dbs_files->{$line} = 1;
878 foreach $filename (</var/lib
/clamav/*>) {
879 my $fn = basename
($filename);
880 next if !$ss_dbs_files->{$fn};
882 my $fh = IO
::File-
>new("<$filename");
883 next if !defined($fh);
886 my $mtime = $st->mtime();
887 $last = $mtime if $mtime > $last;
888 while (defined(my $line = <$fh>)) { $nsigs++; }
893 name
=> 'sanesecurity',
894 type
=> 'unofficial',
895 build_time
=> strftime
("%d %b %Y %H-%M %z", localtime($last)),
904 my $rrd_dir = "/var/lib/rrdcached/db";
905 my $rrdcached_socket = "/var/run/rrdcached.sock";
908 "DS:loadavg:GAUGE:120:0:U",
909 "DS:maxcpu:GAUGE:120:0:U",
910 "DS:cpu:GAUGE:120:0:U",
911 "DS:iowait:GAUGE:120:0:U",
912 "DS:memtotal:GAUGE:120:0:U",
913 "DS:memused:GAUGE:120:0:U",
914 "DS:swaptotal:GAUGE:120:0:U",
915 "DS:swapused:GAUGE:120:0:U",
916 "DS:roottotal:GAUGE:120:0:U",
917 "DS:rootused:GAUGE:120:0:U",
918 "DS:netin:DERIVE:120:0:U",
919 "DS:netout:DERIVE:120:0:U",
921 "RRA:AVERAGE:0.5:1:70", # 1 min avg - one hour
922 "RRA:AVERAGE:0.5:30:70", # 30 min avg - one day
923 "RRA:AVERAGE:0.5:180:70", # 3 hour avg - one week
924 "RRA:AVERAGE:0.5:720:70", # 12 hour avg - one month
925 "RRA:AVERAGE:0.5:10080:70", # 7 day avg - ony year
927 "RRA:MAX:0.5:1:70", # 1 min max - one hour
928 "RRA:MAX:0.5:30:70", # 30 min max - one day
929 "RRA:MAX:0.5:180:70", # 3 hour max - one week
930 "RRA:MAX:0.5:720:70", # 12 hour max - one month
931 "RRA:MAX:0.5:10080:70", # 7 day max - ony year
934 sub cond_create_rrd_file
{
935 my ($filename, $rrddef) = @_;
937 return if -f
$filename;
939 my @args = ($filename);
941 push @args, "--daemon" => "unix:${rrdcached_socket}"
942 if -S
$rrdcached_socket;
944 push @args, '--step', 60;
946 push @args, @$rrddef;
948 # print "TEST: " . join(' ', @args) . "\n";
951 my $err = RRDs
::error
;
952 die "RRD error: $err\n" if $err;
955 sub update_node_status_rrd
{
957 my $filename = "$rrd_dir/pmg-node-v1.rrd";
958 cond_create_rrd_file
($filename, $rrd_def_node);
960 my ($avg1, $avg5, $avg15) = PVE
::ProcFSTools
::read_loadavg
();
962 my $stat = PVE
::ProcFSTools
::read_proc_stat
();
964 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
966 my ($uptime) = PVE
::ProcFSTools
::read_proc_uptime
();
968 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
970 my $maxcpu = $cpuinfo->{cpus
};
972 # traffic from/to physical interface cards
975 foreach my $dev (keys %$netdev) {
976 next if $dev !~ m/^$PVE::Network::PHYSICAL_NIC_RE$/;
977 $netin += $netdev->{$dev}->{receive
};
978 $netout += $netdev->{$dev}->{transmit
};
981 my $meminfo = PVE
::ProcFSTools
::read_meminfo
();
983 my $dinfo = df
('/', 1); # output is bytes
987 # everything not free is considered to be used
988 my $dused = $dinfo->{blocks
} - $dinfo->{bfree
};
990 my $data = "$ctime:$avg1:$maxcpu:$stat->{cpu}:$stat->{wait}:" .
991 "$meminfo->{memtotal}:$meminfo->{memused}:" .
992 "$meminfo->{swaptotal}:$meminfo->{swapused}:" .
993 "$dinfo->{blocks}:$dused:$netin:$netout";
996 my @args = ($filename);
998 push @args, "--daemon" => "unix:${rrdcached_socket}"
999 if -S
$rrdcached_socket;
1003 # print "TEST: " . join(' ', @args) . "\n";
1005 RRDs
::update
(@args);
1006 my $err = RRDs
::error
;
1007 die "RRD error: $err\n" if $err;
1010 sub create_rrd_data
{
1011 my ($rrdname, $timeframe, $cf) = @_;
1013 my $rrd = "${rrd_dir}/$rrdname";
1017 day
=> [ 60*30, 70 ],
1018 week
=> [ 60*180, 70 ],
1019 month
=> [ 60*720, 70 ],
1020 year
=> [ 60*10080, 70 ],
1023 my ($reso, $count) = @{$setup->{$timeframe}};
1024 my $ctime = $reso*int(time()/$reso);
1025 my $req_start = $ctime - $reso*$count;
1027 $cf = "AVERAGE" if !$cf;
1035 push @args, "--daemon" => "unix:${rrdcached_socket}"
1036 if -S
$rrdcached_socket;
1038 my ($start, $step, $names, $data) = RRDs
::fetch
($rrd, $cf, @args);
1040 my $err = RRDs
::error
;
1041 die "RRD error: $err\n" if $err;
1043 die "got wrong time resolution ($step != $reso)\n"
1047 my $fields = scalar(@$names);
1048 for my $line (@$data) {
1049 my $entry = { 'time' => $start };
1051 for (my $i = 0; $i < $fields; $i++) {
1052 my $name = $names->[$i];
1053 if (defined(my $val = $line->[$i])) {
1054 $entry->{$name} = $val;
1056 # leave empty fields undefined
1057 # maybe make this configurable?
1066 sub decode_to_html
{
1067 my ($charset, $data) = @_;
1071 eval { $res = encode_entities
(decode
($charset, $data)); };
1076 sub decode_rfc1522
{
1084 foreach my $r (MIME
::Words
::decode_mimewords
($enc)) {
1088 $res .= decode
($cs, $d);
1101 sub rfc1522_to_html
{
1109 foreach my $r (MIME
::Words
::decode_mimewords
($enc)) {
1113 $res .= encode_entities
(decode
($cs, $d));
1115 $res .= encode_entities
($d);
1126 # RFC 2047 B-ENCODING http://rfc.net/rfc2047.html
1127 # (Q-Encoding is complex and error prone)
1128 sub bencode_header
{
1131 my $CRLF = "\015\012";
1133 # Nonprintables (controls + x7F + 8bit):
1134 my $NONPRINT = "\\x00-\\x1F\\x7F-\\xFF";
1136 # always use utf-8 (work with japanese character sets)
1137 $txt = encode
("UTF-8", $txt);
1139 return $txt if $txt !~ /[$NONPRINT]/o;
1143 while ($txt =~ s/^(.{1,42})//sm) {
1144 my $t = MIME
::Words
::encode_mimeword
($1, 'B', 'UTF-8');
1145 $res .= $res ?
"\015\012\t$t" : $t;
1151 sub load_sa_descriptions
{
1152 my ($additional_dirs) = @_;
1154 my @dirs = ('/usr/share/spamassassin',
1155 '/usr/share/spamassassin-extra');
1157 push @dirs, @$additional_dirs if @$additional_dirs;
1161 my $parse_sa_file = sub {
1164 open(my $fh,'<', $file);
1165 return if !defined($fh);
1167 while (defined(my $line = <$fh>)) {
1168 if ($line =~ m/^(?:\s*)describe\s+(\S+)\s+(.*)\s*$/) {
1169 my ($name, $desc) = ($1, $2);
1170 next if $res->{$name};
1171 $res->{$name}->{desc
} = $desc;
1172 if ($desc =~ m
|[\
(\s
](http
:\
/\/\S
+\
.[^\s\
.\
)]+\
.[^\s\
.\
)]+)|i
) {
1173 $res->{$name}->{url
} = $1;
1180 foreach my $dir (@dirs) {
1181 foreach my $file (<$dir/*.cf
>) {
1182 $parse_sa_file->($file);
1186 $res->{'ClamAVHeuristics'}->{desc
} = "ClamAV heuristic tests";
1194 my $days = int($uptime/86400);
1195 $uptime -= $days*86400;
1197 my $hours = int($uptime/3600);
1198 $uptime -= $hours*3600;
1200 my $mins = $uptime/60;
1203 my $ds = $days > 1 ?
'days' : 'day';
1204 return sprintf "%d $ds %02d:%02d", $days, $hours, $mins;
1206 return sprintf "%02d:%02d", $hours, $mins;
1210 sub finalize_report
{
1211 my ($tt, $template, $data, $mailfrom, $receiver, $debug) = @_;
1215 $tt->process($template, $data, \
$html) ||
1216 die $tt->error() . "\n";
1219 if ($html =~ m
|^\s
*<title
>(.*)</title
>|m
) {
1222 die "unable to extract template title\n";
1225 my $top = MIME
::Entity-
>build(
1226 Type
=> "multipart/related",
1227 To
=> $data->{pmail
},
1229 Subject
=> bencode_header
(decode_entities
($title)));
1233 Type
=> "text/html",
1234 Encoding
=> $debug ?
'binary' : 'quoted-printable');
1240 # we use an empty envelope sender (we don't want to receive NDRs)
1241 PMG
::Utils
::reinject_mail
($top, '', [$receiver], undef, $data->{fqdn
});
1244 sub lookup_timespan
{
1245 my ($timespan) = @_;
1247 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
1248 my $daystart = timelocal
(0, 0, 0, $mday, $mon, $year);
1253 if ($timespan eq 'today') {
1255 $end = $start + 86400;
1256 } elsif ($timespan eq 'yesterday') {
1258 $start = $end - 86400;
1259 } elsif ($timespan eq 'week') {
1261 $start = $end - 7*86400;
1263 die "internal error";
1266 return ($start, $end);
1269 my $rbl_scan_last_cursor;
1270 my $rbl_scan_start_time = time();
1272 sub scan_journal_for_rbl_rejects
{
1274 # example postscreen log entry for RBL rejects
1275 # 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>
1277 # example for PREGREET reject
1278 # Dec 7 06:57:11 proxmox postfix/postscreen[32084]: PREGREET 14 after 0.23 from [x.x.x.x]:63492: EHLO yyyyy\r\n
1280 my $identifier = 'postfix/postscreen';
1283 my $pregreet_count = 0;
1286 my $log = decode_json
(shift);
1288 $rbl_scan_last_cursor = $log->{__CURSOR
} if defined($log->{__CURSOR
});
1290 my $message = $log->{MESSAGE
};
1291 return if !defined($message);
1293 if ($message =~ m/^NOQUEUE:\sreject:.*550 5.7.1 Service unavailable/) {
1295 } elsif ($message =~ m/^PREGREET\s\d+\safter\s/) {
1300 # limit to last 5000 lines to avoid long delays
1301 my $cmd = ['journalctl', '-o', 'json', '--output-fields', '__CURSOR,MESSAGE',
1302 '--no-pager', '--identifier', $identifier, '-n', 5000];
1304 if (defined($rbl_scan_last_cursor)) {
1305 push @$cmd, "--after-cursor=${rbl_scan_last_cursor}";
1307 push @$cmd, "--since=@" . $rbl_scan_start_time;
1310 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1312 return ($rbl_count, $pregreet_count);
1319 return $hwaddress if defined ($hwaddress);
1321 my $fn = '/etc/ssh/ssh_host_rsa_key.pub';
1322 my $sshkey = PVE
::Tools
::file_get_contents
($fn);
1323 $hwaddress = uc(Digest
::MD5
::md5_hex
($sshkey));
1328 my $default_locale = "en_US.UTF-8 UTF-8";
1330 sub cond_add_default_locale
{
1332 my $filename = "/etc/locale.gen";
1334 open(my $infh, "<", $filename) || return;
1336 while (defined(my $line = <$infh>)) {
1337 if ($line =~ m/^\Q${default_locale}\E/) {
1338 # already configured
1343 seek($infh, 0, 0) // return; # seek failed
1345 open(my $outfh, ">", "$filename.tmp") || return;
1348 while (defined(my $line = <$infh>)) {
1349 if ($line =~ m/^#\s*\Q${default_locale}\E.*/) {
1350 print $outfh "${default_locale}\n" if !$done;
1357 print STDERR
"generation pmg default locale\n";
1359 rename("$filename.tmp", $filename) || return; # rename failed
1361 system("dpkg-reconfigure locales -f noninteractive");
1364 sub postgres_admin_cmd
{
1365 my ($cmd, $options, @params) = @_;
1367 $cmd = ref($cmd) ?
$cmd : [ $cmd ];
1369 my $save_uid = POSIX
::getuid
();
1370 my $pg_uid = getpwnam('postgres') || die "getpwnam postgres failed\n";
1372 PVE
::Tools
::setresuid
(-1, $pg_uid, -1) ||
1373 die "setresuid postgres ($pg_uid) failed - $!\n";
1375 PVE
::Tools
::run_command
([@$cmd, '-U', 'postgres', @params], %$options);
1377 PVE
::Tools
::setresuid
(-1, $save_uid, -1) ||
1378 die "setresuid back failed - $!\n";
1381 sub get_pg_server_version
{
1387 # 11.4 (Debian 11.4-1)
1388 # see https://www.postgresql.org/support/versioning/
1389 my ($first_comp) = ($line =~ m/^\s*([0-9]+)/);
1390 if ($first_comp < 10) {
1391 ($major_ver) = ($line =~ m/^([0-9]+\.[0-9]+)\.[0-9]+/);
1393 $major_ver = $first_comp;
1398 postgres_admin_cmd
('psql', { outfunc
=> $parser }, '--quiet',
1399 '--tuples-only', '--no-align', '--command', 'show server_version;');
1402 die "Unable to determine currently running Postgresql server version\n"
1403 if ($@ || !defined($major_ver));
1408 sub reload_smtp_filter
{
1410 my $pid_file = '/run/pmg-smtp-filter.pid';
1411 my $pid = PVE
::Tools
::file_read_firstline
($pid_file);
1415 return 0 if $pid !~ m/^(\d+)$/;
1416 $pid = $1; # untaint
1418 return kill (10, $pid); # send SIGUSR1
1425 foreach my $d (@$domains) {
1426 # skip domains with non-DNS name characters
1427 next if $d =~ m/[^A-Za-z0-9\-\.]/;
1428 if ($d =~ m/^\.(.*)$/) {
1430 $dom =~ s/\./\\\./g;
1432 push @ra, "\.\*\\.$dom";
1439 my $re = join ('|', @ra);
1441 my $regex = qr/\@($re)$/i;
1446 sub read_sa_channel
{
1447 my ($filename) = @_;
1449 my $content = PVE
::Tools
::file_get_contents
($filename);
1451 filename
=> $filename,
1454 ($channel->{keyid
}) = ($content =~ /^KEYID=([a-fA-F0-9]+)$/m);
1455 die "no KEYID in $filename!\n" if !defined($channel->{keyid
});
1456 ($channel->{channelurl
}) = ($content =~ /^CHANNELURL=(.+)$/m);
1457 die "no CHANNELURL in $filename!\n" if !defined($channel->{channelurl
});
1458 ($channel->{gpgkey
}) = ($content =~ /(?:^|\n)(-----BEGIN PGP PUBLIC KEY BLOCK-----.+-----END PGP PUBLIC KEY BLOCK-----)(?:\n|$)/s);
1459 die "no GPG public key in $filename!\n" if !defined($channel->{gpgkey
});
1464 sub local_spamassassin_channels
{
1468 my $local_channel_dir = '/etc/mail/spamassassin/channel.d/';
1470 PVE
::Tools
::dir_glob_foreach
($local_channel_dir, '.*\.conf', sub {
1471 my ($filename) = @_;
1472 my $channel = read_sa_channel
($local_channel_dir.$filename);
1473 push(@$res, $channel);
1479 sub update_local_spamassassin_channels
{
1481 # import all configured channel's gpg-keys to sa-update's keyring
1482 my $localchannels = PMG
::Utils
::local_spamassassin_channels
();
1483 for my $channel (@$localchannels) {
1484 my $importcmd = ['sa-update', '--import', $channel->{filename
}];
1485 push @$importcmd, '-v' if $verbose;
1487 print "Importing gpg key from $channel->{filename}\n" if $verbose;
1488 PVE
::Tools
::run_command
($importcmd);
1491 my $fresh_updates = 0;
1493 for my $channel (@$localchannels) {
1494 my $cmd = ['sa-update', '--channel', $channel->{channelurl
}, '--gpgkey', $channel->{keyid
}];
1495 push @$cmd, '-v' if $verbose;
1497 print "Updating $channel->{channelurl}\n" if $verbose;
1498 my $ret = PVE
::Tools
::run_command
($cmd, noerr
=> 1);
1499 die "updating $channel->{channelurl} failed - sa-update exited with $ret\n" if $ret >= 2;
1501 $fresh_updates = 1 if $ret == 0;
1504 return $fresh_updates