10 use POSIX
qw(strftime);
15 use Time
::HiRes qw
(gettimeofday
);
30 my $msg = shift || '';
38 return $dbh->last_insert_id(
39 undef, undef, undef, undef, { sequence
=> $seq});
43 my ($filename, $lasttime) = @_;
45 my $st = stat($filename);
47 return 0 if !defined($st);
49 return ($lasttime >= $st->ctime);
52 sub extract_filename
{
55 if (my $value = $head->recommended_filename()) {
57 if (my $decvalue = MIME
::Words
::decode_mimewords
($value)) {
58 $decvalue =~ s/\0/ /g;
59 $decvalue = PVE
::Tools
::trim
($decvalue);
68 my ($entity, $add_id, $id) = @_;
72 foreach my $tag (grep {/^x-proxmox-tmp/i} $entity->head->tags) {
73 $entity->head->delete ($tag);
76 $entity->head->replace('X-Proxmox-tmp-AID', $id) if $add_id;
78 foreach my $part ($entity->parts) {
79 $id = remove_marks
($part, $add_id, $id + 1);
90 foreach my $k (keys %$dh) {
93 $body =~ s/__\Q${k}\E__/$v/gs;
101 my ($entity, $sender, $targets, $xforward, $me, $nodsn) = @_;
109 my $smtp = Net
::SMTP-
>new('127.0.0.1', Port
=> 10025, Hello
=> $me) ||
110 die "unable to connect to localhost at port 10025";
112 if (defined($xforward)) {
115 foreach my $attr (keys %{$xforward}) {
116 $xfwd .= " $attr=$xforward->{$attr}";
119 if ($xfwd && $smtp->command("XFORWARD", $xfwd)->response() != CMD_OK
) {
120 syslog
('err', "xforward error - got: %s %s", $smtp->code, scalar($smtp->message));
124 if (!$smtp->mail($sender)) {
125 syslog
('err', "smtp error - got: %s %s", $smtp->code, scalar ($smtp->message));
126 die "smtp from: ERROR";
129 my $dsnopts = $nodsn ?
{Notify
=> ['NEVER']} : {};
131 if (!$smtp->to (@$targets, $dsnopts)) {
132 syslog
('err', "smtp error - got: %s %s", $smtp->code, scalar($smtp->message));
133 die "smtp to: ERROR";
137 #$entity->sync_headers ();
140 my $out = PMG
::SMTPPrinter-
>new($smtp);
141 $entity->print($out);
143 # make sure we always have a newline at the end of the mail
144 # else dataend() fails
145 $smtp->datasend("\n");
147 if ($smtp->dataend()) {
148 my @msgs = $smtp->message;
149 $resmess = $msgs[$#msgs];
150 ($resid) = $resmess =~ m/Ok: queued as ([0-9A-Z]+)/;
151 $rescode = $smtp->code;
153 die sprintf("unexpected SMTP result - got: %s %s : WARNING", $smtp->code, $resmess);
156 my @msgs = $smtp->message;
157 $resmess = $msgs[$#msgs];
158 $rescode = $smtp->code;
159 die sprintf("sending data failed - got: %s %s : ERROR", $smtp->code, $resmess);
164 $smtp->quit if $smtp;
167 syslog
('err', $err);
170 return wantarray ?
($resid, $rescode, $resmess) : $resid;
173 sub analyze_virus_clam
{
174 my ($queue, $dname, $pmg_cfg) = @_;
179 my $clamdscan_opts = "--stdout";
181 my ($csec, $usec) = gettimeofday
();
187 $previous_alarm = alarm($timeout);
190 die "$queue->{logid}: Maximum time ($timeout sec) exceeded. " .
191 "virus analyze (clamav) failed: ERROR";
194 open(CMD
, "/usr/bin/clamdscan $clamdscan_opts '$dname'|") ||
195 die "$queue->{logid}: can't exec clamdscan: $! : ERROR";
200 while (defined(my $line = <CMD
>)) {
201 if ($line =~ m/^$dname.*:\s+([^ :]*)\s+FOUND$/) {
202 # we just use the first detected virus name
203 $vinfo = $1 if !$vinfo;
204 } elsif ($line =~ m/^Infected files:\s(\d*)$/i) {
213 alarm(0); # avoid race conditions
215 if (!defined($ifiles)) {
216 die "$queue->{logid}: got undefined output from " .
217 "virus detector: $response : ERROR";
221 syslog
('info', "$queue->{logid}: virus detected: $vinfo (clamav)");
226 alarm($previous_alarm);
228 my ($csec_end, $usec_end) = gettimeofday
();
229 $queue->{ptime_clam
} =
230 int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
233 syslog
('err', $err);
235 $queue->{errors
} = 1;
238 $queue->{vinfo_clam
} = $vinfo;
240 return $vinfo ?
"$vinfo (clamav)" : undef;
244 my ($queue, $filename, $pmg_cfg, $testmode) = @_;
246 # TODO: support other virus scanners?
248 # always scan with clamav
249 return analyze_virus_clam
($queue, $filename, $pmg_cfg);
252 sub magic_mime_type_for_file
{
255 # we do not use get_mime_type_for_file, because that considers
256 # filename extensions - we only want magic type detection
258 my $bufsize = Xdgmime
::xdg_mime_get_max_buffer_extents
();
259 die "got strange value for max_buffer_extents" if $bufsize > 4096*10;
261 my $ct = "application/octet-stream";
263 my $fh = IO
::File-
>new("<$filename") ||
264 die "unable to open file '$filename' - $!";
267 if (($len = $fh->read($buf, $bufsize)) > 0) {
268 $ct = xdg_mime_get_mime_type_for_data
($buf, $len);
272 die "unable to read file '$filename' - $!" if ($len < 0);
280 if (my $path = $entity->{PMX_decoded_path
}) {
282 # set a reasonable default if magic does not give a result
283 $entity->{PMX_magic_ct
} = $entity->head->mime_attr('content-type');
285 if (my $ct = magic_mime_type_for_file
($path)) {
286 if ($ct ne 'application/octet-stream' || !$entity->{PMX_magic_ct
}) {
287 $entity->{PMX_magic_ct
} = $ct;
291 my $filename = $entity->head->recommended_filename;
292 $filename = basename
($path) if !defined($filename) || $filename eq '';
294 if (my $ct = xdg_mime_get_mime_type_from_file_name
($filename)) {
295 $entity->{PMX_glob_ct
} = $ct;
299 foreach my $part ($entity->parts) {
300 add_ct_marks
($part);
304 # x509 certificate utils
306 # only write output if something fails
312 my $record_output = sub {
318 PVE
::Tools
::run_command
($cmd, outfunc
=> $record_output,
319 errfunc
=> $record_output);
324 print STDERR
$outbuf;
329 my $proxmox_tls_cert_fn = "/etc/pmg/pmg-tls.pem";
331 sub gen_proxmox_tls_cert
{
334 my $resolv = PVE
::INotify
::read_file
('resolvconf');
335 my $domain = $resolv->{search
};
337 my $company = $domain; # what else ?
338 my $cn = "*.$domain";
340 return if !$force && -f
$proxmox_tls_cert_fn;
342 my $sslconf = <<__EOD__;
343 RANDFILE = /root/.rnd
348 distinguished_name = req_distinguished_name
349 req_extensions = v3_req
351 string_mask = nombstr
353 [ req_distinguished_name ]
354 organizationalUnitName = Proxmox Mail Gateway
355 organizationName = $company
359 basicConstraints = CA:FALSE
361 keyUsage = nonRepudiation, digitalSignature, keyEncipherment
364 my $cfgfn = "/tmp/pmgtlsconf-$$.tmp";
365 my $fh = IO
::File-
>new ($cfgfn, "w");
370 my $cmd = ['openssl', 'req', '-batch', '-x509', '-new', '-sha256',
371 '-config', $cfgfn, '-days', 3650, '-nodes',
372 '-out', $proxmox_tls_cert_fn,
373 '-keyout', $proxmox_tls_cert_fn];
374 run_silent_cmd
($cmd);
378 unlink $proxmox_tls_cert_fn;
380 die "unable to generate proxmox certificate request:\n$err";
386 sub find_local_network_for_ip
{
389 my $testip = Net
::IP-
>new($ip);
391 my $isv6 = $testip->version == 6;
393 PVE
::ProcFSTools
::read_proc_net_ipv6_route
() :
394 PVE
::ProcFSTools
::read_proc_net_route
();
396 foreach my $entry (@$routes) {
399 $mask = $entry->{prefix
};
400 next if !$mask; # skip the default route...
402 $mask = $PVE::Network
::ipv4_mask_hash_localnet-
>{$entry->{mask
}};
403 next if !defined($mask);
405 my $cidr = "$entry->{dest}/$mask";
406 my $testnet = Net
::IP-
>new($cidr);
407 my $overlap = $testnet->overlaps($testip);
408 if ($overlap == $Net::IP
::IP_B_IN_A_OVERLAP
||
409 $overlap == $Net::IP
::IP_IDENTICAL
)
415 die "unable to detect local network for ip '$ip'\n";
419 my ($service, $cmd) = @_;
421 die "unknown service command '$cmd'\n"
422 if $cmd !~ m/^(start|stop|restart|reload)$/;
424 if ($service eq 'pmgdaemon' || $service eq 'pmgproxy') {
425 if ($cmd eq 'restart') {
428 die "invalid service cmd '$service $cmd': ERROR";
432 $service = 'postfix@-' if $service eq 'postfix';
433 PVE
::Tools
::run_command
(['systemctl', $cmd, $service]);
436 # this is also used to get the IP of the local node
438 my ($nodename, $noerr) = @_;
440 my ($family, $packed_ip);
443 my @res = PVE
::Tools
::getaddrinfo_all
($nodename);
444 $family = $res[0]->{family
};
445 $packed_ip = (PVE
::Tools
::unpack_sockaddr_in46
($res[0]->{addr
}))[2];
449 die "hostname lookup failed:\n$@" if !$noerr;
453 my $ip = Socket
::inet_ntop
($family, $packed_ip);
454 if ($ip =~ m/^127\.|^::1$/) {
455 die "hostname lookup failed - got local IP address ($nodename = $ip)\n" if !$noerr;
459 return wantarray ?
($ip, $family) : $ip;
465 # make sure the file exists (else postmap fails)
466 IO
::File-
>new($filename, 'a', 0644);
469 PVE
::Tools
::run_command
(
470 ['/usr/sbin/postmap', $filename],
471 errmsg
=> "unable to update postfix table $filename");
482 my $read_cvd_info = sub {
483 my ($dbname, $dbfile) = @_;
486 my $fh = IO
::File-
>new("<$dbfile");
488 warn "cant open ClamAV Database $dbname ($dbfile) - $!\n";
491 $fh->read($header, 512);
494 ## ClamAV-VDB:16 Mar 2016 23-17 +0000:57:4218790:60:06386f34a16ebeea2733ab037f0536be:
495 if ($header =~ m/^(ClamAV-VDB):([^:]+):(\d+):(\d+):/) {
496 my ($ftype, $btime, $version, $nsigs) = ($1, $2, $3, $4);
500 build_time
=> $btime,
505 warn "unable to parse ClamAV Database $dbname ($dbfile)\n";
510 my $filename = "/var/lib/clamav/main.inc/main.info";
511 $filename = "/var/lib/clamav/main.cvd" if ! -f
$filename;
513 $read_cvd_info->('main', $filename) if -f
$filename;
516 $filename = "/var/lib/clamav/daily.inc/daily.info";
517 $filename = "/var/lib/clamav/daily.cvd" if ! -f
$filename;
518 $filename = "/var/lib/clamav/daily.cld" if ! -f
$filename;
520 $read_cvd_info->('daily', $filename) if -f
$filename;
522 $filename = "/var/lib/clamav/bytecode.cvd";
523 $read_cvd_info->('bytecode', $filename) if -f
$filename;
527 foreach $filename (</var/lib
/clamav/*>) {
528 next if $filename !~ m/\.(ndb|hdb)$/;
529 my $fh = IO
::File-
>new("<$filename");
530 next if !defined($fh);
533 my $mtime = $st->mtime();
534 $last = $mtime if $mtime > $last;
535 while (defined(my $line = <$fh>)) { $nsigs++; }
540 name
=> 'Sanesecurity',
541 type
=> 'unofficial',
542 build_time
=> strftime
("%d %b %Y %H-%M", localtime($last)),