]> git.proxmox.com Git - pmg-api.git/blame - PMG/Utils.pm
fix bug #1625 - change default rule priorities
[pmg-api.git] / PMG / Utils.pm
CommitLineData
758c7b6b
DM
1package PMG::Utils;
2
3use strict;
4use warnings;
758c7b6b 5use DBI;
b8ea5d5d 6use Net::Cmd;
758c7b6b 7use Net::SMTP;
26357b0a 8use IO::File;
cad3d400 9use File::stat;
d17c5265
DM
10use POSIX qw(strftime);
11use File::stat;
ff1c5a81 12use File::Basename;
758c7b6b
DM
13use MIME::Words;
14use MIME::Parser;
8210c7fa 15use Time::HiRes qw (gettimeofday);
2f7031b7 16use Time::Local;
26357b0a 17use Xdgmime;
d0d91cda 18use Data::Dumper;
62ebb4bc 19use Digest::SHA;
5d5af7c5 20use Digest::MD5;
f609bf7f 21use Net::IP;
9f67f5b3 22use Socket;
dff363d9
DM
23use RRDs;
24use Filesys::Df;
8208c076 25use Encode;
9a56f771 26use HTML::Entities;
758c7b6b 27
dff363d9 28use PVE::ProcFSTools;
f609bf7f 29use PVE::Network;
5953119e 30use PVE::Tools;
758c7b6b 31use PVE::SafeSyslog;
f609bf7f 32use PVE::ProcFSTools;
d0d91cda 33use PMG::AtomicFile;
8210c7fa 34use PMG::MailQueue;
c4df1b85 35use PMG::SMTPPrinter;
758c7b6b 36
6c54c10a 37my $valid_pmg_realms = ['pam', 'pmg', 'quarantine'];
62ebb4bc
DM
38
39PVE::JSONSchema::register_standard_option('realm', {
40 description => "Authentication domain ID",
6c54c10a
DM
41 type => 'string',
42 enum => $valid_pmg_realms,
62ebb4bc
DM
43 maxLength => 32,
44});
45
6214b5cf
DM
46PVE::JSONSchema::register_standard_option('pmg-starttime', {
47 description => "Only consider entries newer than 'starttime' (unix epoch). Default is 'now - 1day'.",
48 type => 'integer',
49 minimum => 0,
50 optional => 1,
51});
52
53PVE::JSONSchema::register_standard_option('pmg-endtime', {
54 description => "Only consider entries older than 'endtime' (unix epoch). This is set to '<start> + 1day' by default.",
55 type => 'integer',
56 minimum => 1,
57 optional => 1,
58});
59
62ebb4bc
DM
60PVE::JSONSchema::register_format('pmg-userid', \&verify_username);
61sub verify_username {
62 my ($username, $noerr) = @_;
63
64 $username = '' if !$username;
65 my $len = length($username);
66 if ($len < 3) {
67 die "user name '$username' is too short\n" if !$noerr;
68 return undef;
69 }
70 if ($len > 64) {
71 die "user name '$username' is too long ($len > 64)\n" if !$noerr;
72 return undef;
73 }
74
75 # we only allow a limited set of characters
76 # colon is not allowed, because we store usernames in
77 # colon separated lists)!
78 # slash is not allowed because it is used as pve API delimiter
79 # also see "man useradd"
6c54c10a
DM
80 my $realm_list = join('|', @$valid_pmg_realms);
81 if ($username =~ m!^([^\s:/]+)\@(${realm_list})$!) {
62ebb4bc
DM
82 return wantarray ? ($username, $1, $2) : $username;
83 }
84
85 die "value '$username' does not look like a valid user name\n" if !$noerr;
86
87 return undef;
88}
89
90PVE::JSONSchema::register_standard_option('userid', {
91 description => "User ID",
92 type => 'string', format => 'pmg-userid',
6b0180c3 93 minLength => 4,
62ebb4bc 94 maxLength => 64,
6b0180c3 95});
62ebb4bc
DM
96
97PVE::JSONSchema::register_standard_option('username', {
98 description => "Username (without realm)",
99 type => 'string',
100 pattern => '[^\s:\/\@]{3,60}',
6b0180c3 101 minLength => 4,
62ebb4bc
DM
102 maxLength => 64,
103});
104
01929101
DM
105PVE::JSONSchema::register_standard_option('pmg-email-address', {
106 description => "Email Address (allow most characters).",
107 type => 'string',
108 pattern => '(?:|[^\s\/\@]+\@[^\s\/\@]+)',
109 maxLength => 512,
110 minLength => 3,
111});
112
758c7b6b
DM
113sub lastid {
114 my ($dbh, $seq) = @_;
115
116 return $dbh->last_insert_id(
117 undef, undef, undef, undef, { sequence => $seq});
118}
119
ab466078
DM
120# quote all regex operators
121sub quote_regex {
122 my $val = shift;
123
124 $val =~ s/([\(\)\[\]\/\}\+\*\?\.\|\^\$\\])/\\$1/g;
125
126 return $val;
127}
128
cad3d400
DM
129sub file_older_than {
130 my ($filename, $lasttime) = @_;
131
132 my $st = stat($filename);
133
134 return 0 if !defined($st);
135
136 return ($lasttime >= $st->ctime);
137}
138
758c7b6b
DM
139sub extract_filename {
140 my ($head) = @_;
141
142 if (my $value = $head->recommended_filename()) {
8210c7fa 143 chomp $value;
758c7b6b
DM
144 if (my $decvalue = MIME::Words::decode_mimewords($value)) {
145 $decvalue =~ s/\0/ /g;
5953119e 146 $decvalue = PVE::Tools::trim($decvalue);
758c7b6b
DM
147 return $decvalue;
148 }
149 }
150
151 return undef;
152}
153
154sub remove_marks {
155 my ($entity, $add_id, $id) = @_;
156
157 $id //= 1;
158
159 foreach my $tag (grep {/^x-proxmox-tmp/i} $entity->head->tags) {
160 $entity->head->delete ($tag);
161 }
162
163 $entity->head->replace('X-Proxmox-tmp-AID', $id) if $add_id;
164
165 foreach my $part ($entity->parts) {
166 $id = remove_marks($part, $add_id, $id + 1);
167 }
168
169 return $id;
170}
171
172sub subst_values {
173 my ($body, $dh) = @_;
174
175 return if !$body;
176
177 foreach my $k (keys %$dh) {
178 my $v = $dh->{$k};
bd98f5a1
DM
179 if (defined($v)) {
180 $body =~ s/__\Q${k}\E__/$v/gs;
758c7b6b
DM
181 }
182 }
183
184 return $body;
185}
186
187sub reinject_mail {
188 my ($entity, $sender, $targets, $xforward, $me, $nodsn) = @_;
189
190 my $smtp;
191 my $resid;
192 my $rescode;
193 my $resmess;
194
195 eval {
196 my $smtp = Net::SMTP->new('127.0.0.1', Port => 10025, Hello => $me) ||
197 die "unable to connect to localhost at port 10025";
198
199 if (defined($xforward)) {
200 my $xfwd;
8210c7fa 201
758c7b6b
DM
202 foreach my $attr (keys %{$xforward}) {
203 $xfwd .= " $attr=$xforward->{$attr}";
204 }
205
206 if ($xfwd && $smtp->command("XFORWARD", $xfwd)->response() != CMD_OK) {
207 syslog('err', "xforward error - got: %s %s", $smtp->code, scalar($smtp->message));
208 }
209 }
210
211 if (!$smtp->mail($sender)) {
212 syslog('err', "smtp error - got: %s %s", $smtp->code, scalar ($smtp->message));
213 die "smtp from: ERROR";
214 }
215
216 my $dsnopts = $nodsn ? {Notify => ['NEVER']} : {};
217
218 if (!$smtp->to (@$targets, $dsnopts)) {
219 syslog ('err', "smtp error - got: %s %s", $smtp->code, scalar($smtp->message));
220 die "smtp to: ERROR";
221 }
222
223 # Output the head:
224 #$entity->sync_headers ();
225 $smtp->data();
226
227 my $out = PMG::SMTPPrinter->new($smtp);
228 $entity->print($out);
8210c7fa
DM
229
230 # make sure we always have a newline at the end of the mail
758c7b6b
DM
231 # else dataend() fails
232 $smtp->datasend("\n");
233
234 if ($smtp->dataend()) {
235 my @msgs = $smtp->message;
8210c7fa
DM
236 $resmess = $msgs[$#msgs];
237 ($resid) = $resmess =~ m/Ok: queued as ([0-9A-Z]+)/;
758c7b6b
DM
238 $rescode = $smtp->code;
239 if (!$resid) {
240 die sprintf("unexpected SMTP result - got: %s %s : WARNING", $smtp->code, $resmess);
8210c7fa 241 }
758c7b6b
DM
242 } else {
243 my @msgs = $smtp->message;
8210c7fa 244 $resmess = $msgs[$#msgs];
758c7b6b
DM
245 $rescode = $smtp->code;
246 die sprintf("sending data failed - got: %s %s : ERROR", $smtp->code, $resmess);
247 }
248 };
249 my $err = $@;
8210c7fa 250
758c7b6b 251 $smtp->quit if $smtp;
8210c7fa 252
758c7b6b
DM
253 if ($err) {
254 syslog ('err', $err);
255 }
256
257 return wantarray ? ($resid, $rescode, $resmess) : $resid;
258}
259
8210c7fa
DM
260sub analyze_virus_clam {
261 my ($queue, $dname, $pmg_cfg) = @_;
262
263 my $timeout = 60*5;
264 my $vinfo;
265
266 my $clamdscan_opts = "--stdout";
267
268 my ($csec, $usec) = gettimeofday();
269
270 my $previous_alarm;
271
272 eval {
273
274 $previous_alarm = alarm($timeout);
275
276 $SIG{ALRM} = sub {
277 die "$queue->{logid}: Maximum time ($timeout sec) exceeded. " .
278 "virus analyze (clamav) failed: ERROR";
279 };
280
281 open(CMD, "/usr/bin/clamdscan $clamdscan_opts '$dname'|") ||
282 die "$queue->{logid}: can't exec clamdscan: $! : ERROR";
283
284 my $ifiles;
8210c7fa 285
54eaf7df
DM
286 my $response = '';
287 while (defined(my $line = <CMD>)) {
288 if ($line =~ m/^$dname.*:\s+([^ :]*)\s+FOUND$/) {
8210c7fa
DM
289 # we just use the first detected virus name
290 $vinfo = $1 if !$vinfo;
54eaf7df 291 } elsif ($line =~ m/^Infected files:\s(\d*)$/i) {
8210c7fa
DM
292 $ifiles = $1;
293 }
294
54eaf7df 295 $response .= $line;
8210c7fa
DM
296 }
297
298 close(CMD);
299
300 alarm(0); # avoid race conditions
301
302 if (!defined($ifiles)) {
303 die "$queue->{logid}: got undefined output from " .
54eaf7df 304 "virus detector: $response : ERROR";
8210c7fa
DM
305 }
306
307 if ($vinfo) {
54eaf7df 308 syslog('info', "$queue->{logid}: virus detected: $vinfo (clamav)");
8210c7fa
DM
309 }
310 };
311 my $err = $@;
312
313 alarm($previous_alarm);
314
315 my ($csec_end, $usec_end) = gettimeofday();
316 $queue->{ptime_clam} =
317 int (($csec_end-$csec)*1000 + ($usec_end - $usec)/1000);
318
319 if ($err) {
320 syslog ('err', $err);
321 $vinfo = undef;
322 $queue->{errors} = 1;
323 }
324
325 $queue->{vinfo_clam} = $vinfo;
326
327 return $vinfo ? "$vinfo (clamav)" : undef;
328}
329
330sub analyze_virus {
331 my ($queue, $filename, $pmg_cfg, $testmode) = @_;
332
333 # TODO: support other virus scanners?
334
335 # always scan with clamav
336 return analyze_virus_clam($queue, $filename, $pmg_cfg);
337}
338
26357b0a
DM
339sub magic_mime_type_for_file {
340 my ($filename) = @_;
dff363d9 341
26357b0a
DM
342 # we do not use get_mime_type_for_file, because that considers
343 # filename extensions - we only want magic type detection
344
345 my $bufsize = Xdgmime::xdg_mime_get_max_buffer_extents();
346 die "got strange value for max_buffer_extents" if $bufsize > 4096*10;
347
348 my $ct = "application/octet-stream";
349
dff363d9 350 my $fh = IO::File->new("<$filename") ||
26357b0a
DM
351 die "unable to open file '$filename' - $!";
352
353 my ($buf, $len);
354 if (($len = $fh->read($buf, $bufsize)) > 0) {
355 $ct = xdg_mime_get_mime_type_for_data($buf, $len);
356 }
357 $fh->close();
dff363d9 358
26357b0a 359 die "unable to read file '$filename' - $!" if ($len < 0);
dff363d9 360
26357b0a
DM
361 return $ct;
362}
758c7b6b 363
1d4193a1
DM
364sub add_ct_marks {
365 my ($entity) = @_;
366
367 if (my $path = $entity->{PMX_decoded_path}) {
368
369 # set a reasonable default if magic does not give a result
370 $entity->{PMX_magic_ct} = $entity->head->mime_attr('content-type');
371
372 if (my $ct = magic_mime_type_for_file($path)) {
373 if ($ct ne 'application/octet-stream' || !$entity->{PMX_magic_ct}) {
374 $entity->{PMX_magic_ct} = $ct;
375 }
376 }
377
378 my $filename = $entity->head->recommended_filename;
379 $filename = basename($path) if !defined($filename) || $filename eq '';
380
381 if (my $ct = xdg_mime_get_mime_type_from_file_name($filename)) {
382 $entity->{PMX_glob_ct} = $ct;
383 }
384 }
385
386 foreach my $part ($entity->parts) {
387 add_ct_marks ($part);
388 }
389}
390
f609bf7f
DM
391# x509 certificate utils
392
896ef634
DM
393# only write output if something fails
394sub run_silent_cmd {
395 my ($cmd) = @_;
396
397 my $outbuf = '';
398
399 my $record_output = sub {
400 $outbuf .= shift;
401 $outbuf .= "\n";
402 };
403
404 eval {
405 PVE::Tools::run_command($cmd, outfunc => $record_output,
406 errfunc => $record_output);
407 };
408 my $err = $@;
409
410 if ($err) {
411 print STDERR $outbuf;
412 die $err;
413 }
414}
415
3278b571 416my $proxmox_tls_cert_fn = "/etc/pmg/pmg-tls.pem";
f609bf7f
DM
417
418sub gen_proxmox_tls_cert {
bc44eb02 419 my ($force) = @_;
f609bf7f 420
bc44eb02
DM
421 my $resolv = PVE::INotify::read_file('resolvconf');
422 my $domain = $resolv->{search};
423
424 my $company = $domain; # what else ?
425 my $cn = "*.$domain";
426
427 return if !$force && -f $proxmox_tls_cert_fn;
f609bf7f
DM
428
429 my $sslconf = <<__EOD__;
430RANDFILE = /root/.rnd
431extensions = v3_req
432
433[ req ]
434default_bits = 4096
435distinguished_name = req_distinguished_name
436req_extensions = v3_req
437prompt = no
438string_mask = nombstr
439
440[ req_distinguished_name ]
441organizationalUnitName = Proxmox Mail Gateway
442organizationName = $company
443commonName = $cn
444
445[ v3_req ]
446basicConstraints = CA:FALSE
447nsCertType = server
448keyUsage = nonRepudiation, digitalSignature, keyEncipherment
449__EOD__
450
3278b571 451 my $cfgfn = "/tmp/pmgtlsconf-$$.tmp";
f609bf7f
DM
452 my $fh = IO::File->new ($cfgfn, "w");
453 print $fh $sslconf;
454 close ($fh);
455
456 eval {
896ef634
DM
457 my $cmd = ['openssl', 'req', '-batch', '-x509', '-new', '-sha256',
458 '-config', $cfgfn, '-days', 3650, '-nodes',
459 '-out', $proxmox_tls_cert_fn,
460 '-keyout', $proxmox_tls_cert_fn];
461 run_silent_cmd($cmd);
f609bf7f
DM
462 };
463
464 if (my $err = $@) {
465 unlink $proxmox_tls_cert_fn;
466 unlink $cfgfn;
467 die "unable to generate proxmox certificate request:\n$err";
468 }
469
470 unlink $cfgfn;
471}
472
473sub find_local_network_for_ip {
474 my ($ip) = @_;
475
476 my $testip = Net::IP->new($ip);
477
478 my $isv6 = $testip->version == 6;
479 my $routes = $isv6 ?
480 PVE::ProcFSTools::read_proc_net_ipv6_route() :
481 PVE::ProcFSTools::read_proc_net_route();
482
483 foreach my $entry (@$routes) {
484 my $mask;
485 if ($isv6) {
486 $mask = $entry->{prefix};
487 next if !$mask; # skip the default route...
488 } else {
489 $mask = $PVE::Network::ipv4_mask_hash_localnet->{$entry->{mask}};
490 next if !defined($mask);
491 }
492 my $cidr = "$entry->{dest}/$mask";
493 my $testnet = Net::IP->new($cidr);
494 my $overlap = $testnet->overlaps($testip);
495 if ($overlap == $Net::IP::IP_B_IN_A_OVERLAP ||
496 $overlap == $Net::IP::IP_IDENTICAL)
497 {
498 return $cidr;
499 }
500 }
501
502 die "unable to detect local network for ip '$ip'\n";
503}
d0d91cda 504
ef07e4d0
DM
505my $service_aliases = {
506 'postfix' => 'postfix@-',
507 'postgres' => 'postgresql@9.6-main',
508};
509
510sub lookup_real_service_name {
511 my $alias = shift;
512
513 return $service_aliases->{$alias} // $alias;
514}
515
230b4e03
DM
516sub get_full_service_state {
517 my ($service) = @_;
518
519 my $res;
520
521 my $parser = sub {
522 my $line = shift;
523 if ($line =~ m/^([^=\s]+)=(.*)$/) {
524 $res->{$1} = $2;
525 }
526 };
527
ef07e4d0 528 $service = $service_aliases->{$service} // $service;
230b4e03
DM
529 PVE::Tools::run_command(['systemctl', 'show', $service], outfunc => $parser);
530
531 return $res;
532}
533
00d8b7f7
DM
534our $db_service_list = [
535 'pmgpolicy', 'pmgmirror', 'pmgtunnel', 'pmg-smtp-filter' ];
536
cfdf6608
DM
537sub service_wait_stopped {
538 my ($timeout, $service_list) = @_;
539
540 my $starttime = time();
541
542 foreach my $service (@$service_list) {
543 PVE::Tools::run_command(['systemctl', 'stop', $service]);
544 }
545
546 while (1) {
547 my $wait = 0;
548
549 foreach my $service (@$service_list) {
550 my $ss = get_full_service_state($service);
551 my $state = $ss->{ActiveState} // 'unknown';
552
553 if ($state ne 'inactive') {
554 if ((time() - $starttime) > $timeout) {
555 syslog('err', "unable to stop services (got timeout)");
556 $wait = 0;
557 last;
558 }
559 $wait = 1;
560 }
561 }
562
563 last if !$wait;
564
565 sleep(1);
566 }
567}
568
3f85510e
DM
569sub service_cmd {
570 my ($service, $cmd) = @_;
571
572 die "unknown service command '$cmd'\n"
f6884917 573 if $cmd !~ m/^(start|stop|restart|reload|reload-or-restart)$/;
3f85510e
DM
574
575 if ($service eq 'pmgdaemon' || $service eq 'pmgproxy') {
f6884917 576 die "invalid service cmd '$service $cmd': ERROR" if $cmd eq 'stop';
81fa07d9
DM
577 } elsif ($service eq 'fetchmail') {
578 # use restart instead of start - else it does not start 'exited' unit
579 # after setting START_DAEMON=yes in /etc/default/fetchmail
580 $cmd = 'restart' if $cmd eq 'start';
3f85510e
DM
581 }
582
ef07e4d0 583 $service = $service_aliases->{$service} // $service;
3f85510e
DM
584 PVE::Tools::run_command(['systemctl', $cmd, $service]);
585};
586
9f67f5b3
DM
587# this is also used to get the IP of the local node
588sub lookup_node_ip {
589 my ($nodename, $noerr) = @_;
590
591 my ($family, $packed_ip);
592
593 eval {
594 my @res = PVE::Tools::getaddrinfo_all($nodename);
595 $family = $res[0]->{family};
596 $packed_ip = (PVE::Tools::unpack_sockaddr_in46($res[0]->{addr}))[2];
597 };
598
599 if ($@) {
600 die "hostname lookup failed:\n$@" if !$noerr;
601 return undef;
602 }
603
604 my $ip = Socket::inet_ntop($family, $packed_ip);
605 if ($ip =~ m/^127\.|^::1$/) {
606 die "hostname lookup failed - got local IP address ($nodename = $ip)\n" if !$noerr;
607 return undef;
608 }
609
610 return wantarray ? ($ip, $family) : $ip;
611}
612
630d1ae3
DM
613sub run_postmap {
614 my ($filename) = @_;
615
616 # make sure the file exists (else postmap fails)
617 IO::File->new($filename, 'a', 0644);
618
78982d93
DM
619 my $age_src = -M $filename // 0;
620 my $age_dst = -M "$filename.db" // 10000000000;
621
622 # if not changed, do nothing
623 return if $age_src > $age_dst;
624
630d1ae3
DM
625 eval {
626 PVE::Tools::run_command(
627 ['/usr/sbin/postmap', $filename],
628 errmsg => "unable to update postfix table $filename");
629 };
630 my $err = $@;
631
632 warn $err if $err;
633}
634
d17c5265
DM
635sub clamav_dbstat {
636
637 my $res = [];
638
639 my $read_cvd_info = sub {
640 my ($dbname, $dbfile) = @_;
641
642 my $header;
643 my $fh = IO::File->new("<$dbfile");
644 if (!$fh) {
645 warn "cant open ClamAV Database $dbname ($dbfile) - $!\n";
646 return;
647 }
648 $fh->read($header, 512);
649 $fh->close();
650
651 ## ClamAV-VDB:16 Mar 2016 23-17 +0000:57:4218790:60:06386f34a16ebeea2733ab037f0536be:
652 if ($header =~ m/^(ClamAV-VDB):([^:]+):(\d+):(\d+):/) {
653 my ($ftype, $btime, $version, $nsigs) = ($1, $2, $3, $4);
654 push @$res, {
655 name => $dbname,
656 type => $ftype,
657 build_time => $btime,
658 version => $version,
659 nsigs => $nsigs,
660 };
661 } else {
662 warn "unable to parse ClamAV Database $dbname ($dbfile)\n";
663 }
664 };
665
666 # main database
667 my $filename = "/var/lib/clamav/main.inc/main.info";
668 $filename = "/var/lib/clamav/main.cvd" if ! -f $filename;
669
670 $read_cvd_info->('main', $filename) if -f $filename;
671
672 # daily database
673 $filename = "/var/lib/clamav/daily.inc/daily.info";
674 $filename = "/var/lib/clamav/daily.cvd" if ! -f $filename;
675 $filename = "/var/lib/clamav/daily.cld" if ! -f $filename;
676
677 $read_cvd_info->('daily', $filename) if -f $filename;
678
679 $filename = "/var/lib/clamav/bytecode.cvd";
680 $read_cvd_info->('bytecode', $filename) if -f $filename;
681
9860e592
DM
682 $filename = "/var/lib/clamav/safebrowsing.cvd";
683 $read_cvd_info->('safebrowsing', $filename) if -f $filename;
684
dabcd20e
DM
685 my $ss_dbs_fn = "/var/lib/clamav-unofficial-sigs/configs/ss-include-dbs.txt";
686 my $ss_dbs_files = {};
687 if (my $ssfh = IO::File->new("<${ss_dbs_fn}")) {
688 while (defined(my $line = <$ssfh>)) {
689 chomp $line;
690 $ss_dbs_files->{$line} = 1;
691 }
692 }
d17c5265
DM
693 my $last = 0;
694 my $nsigs = 0;
695 foreach $filename (</var/lib/clamav/*>) {
dabcd20e
DM
696 my $fn = basename($filename);
697 next if !$ss_dbs_files->{$fn};
698
d17c5265
DM
699 my $fh = IO::File->new("<$filename");
700 next if !defined($fh);
701 my $st = stat($fh);
702 next if !$st;
703 my $mtime = $st->mtime();
704 $last = $mtime if $mtime > $last;
705 while (defined(my $line = <$fh>)) { $nsigs++; }
706 }
707
708 if ($nsigs > 0) {
709 push @$res, {
9860e592 710 name => 'sanesecurity',
d17c5265 711 type => 'unofficial',
2d011fef 712 build_time => strftime("%d %b %Y %H-%M %z", localtime($last)),
d17c5265
DM
713 nsigs => $nsigs,
714 };
715 }
716
717 return $res;
718}
719
dff363d9
DM
720# RRD related code
721my $rrd_dir = "/var/lib/rrdcached/db";
722my $rrdcached_socket = "/var/run/rrdcached.sock";
723
724my $rrd_def_node = [
725 "DS:loadavg:GAUGE:120:0:U",
726 "DS:maxcpu:GAUGE:120:0:U",
727 "DS:cpu:GAUGE:120:0:U",
728 "DS:iowait:GAUGE:120:0:U",
729 "DS:memtotal:GAUGE:120:0:U",
730 "DS:memused:GAUGE:120:0:U",
731 "DS:swaptotal:GAUGE:120:0:U",
732 "DS:swapused:GAUGE:120:0:U",
733 "DS:roottotal:GAUGE:120:0:U",
734 "DS:rootused:GAUGE:120:0:U",
735 "DS:netin:DERIVE:120:0:U",
736 "DS:netout:DERIVE:120:0:U",
737
738 "RRA:AVERAGE:0.5:1:70", # 1 min avg - one hour
739 "RRA:AVERAGE:0.5:30:70", # 30 min avg - one day
740 "RRA:AVERAGE:0.5:180:70", # 3 hour avg - one week
741 "RRA:AVERAGE:0.5:720:70", # 12 hour avg - one month
742 "RRA:AVERAGE:0.5:10080:70", # 7 day avg - ony year
743
744 "RRA:MAX:0.5:1:70", # 1 min max - one hour
745 "RRA:MAX:0.5:30:70", # 30 min max - one day
746 "RRA:MAX:0.5:180:70", # 3 hour max - one week
747 "RRA:MAX:0.5:720:70", # 12 hour max - one month
748 "RRA:MAX:0.5:10080:70", # 7 day max - ony year
749];
750
751sub cond_create_rrd_file {
752 my ($filename, $rrddef) = @_;
753
754 return if -f $filename;
755
756 my @args = ($filename);
757
758 push @args, "--daemon" => "unix:${rrdcached_socket}"
759 if -S $rrdcached_socket;
760
761 push @args, '--step', 60;
762
763 push @args, @$rrddef;
764
765 # print "TEST: " . join(' ', @args) . "\n";
766
767 RRDs::create(@args);
768 my $err = RRDs::error;
769 die "RRD error: $err\n" if $err;
770}
771
772sub update_node_status_rrd {
773
774 my $filename = "$rrd_dir/pmg-node-v1.rrd";
775 cond_create_rrd_file($filename, $rrd_def_node);
776
777 my ($avg1, $avg5, $avg15) = PVE::ProcFSTools::read_loadavg();
778
779 my $stat = PVE::ProcFSTools::read_proc_stat();
780
781 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
782
783 my ($uptime) = PVE::ProcFSTools::read_proc_uptime();
784
785 my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
786
787 my $maxcpu = $cpuinfo->{cpus};
788
789 # traffic from/to physical interface cards
790 my $netin = 0;
791 my $netout = 0;
792 foreach my $dev (keys %$netdev) {
170295f8 793 next if $dev !~ m/^$PVE::Network::PHYSICAL_NIC_RE$/;
dff363d9
DM
794 $netin += $netdev->{$dev}->{receive};
795 $netout += $netdev->{$dev}->{transmit};
796 }
797
798 my $meminfo = PVE::ProcFSTools::read_meminfo();
799
800 my $dinfo = df('/', 1); # output is bytes
801
802 my $ctime = time();
803
804 # everything not free is considered to be used
805 my $dused = $dinfo->{blocks} - $dinfo->{bfree};
806
807 my $data = "$ctime:$avg1:$maxcpu:$stat->{cpu}:$stat->{wait}:" .
808 "$meminfo->{memtotal}:$meminfo->{memused}:" .
809 "$meminfo->{swaptotal}:$meminfo->{swapused}:" .
810 "$dinfo->{blocks}:$dused:$netin:$netout";
811
812
813 my @args = ($filename);
814
815 push @args, "--daemon" => "unix:${rrdcached_socket}"
816 if -S $rrdcached_socket;
817
818 push @args, $data;
819
820 # print "TEST: " . join(' ', @args) . "\n";
821
822 RRDs::update(@args);
823 my $err = RRDs::error;
824 die "RRD error: $err\n" if $err;
825}
826
065b2986
DM
827sub create_rrd_data {
828 my ($rrdname, $timeframe, $cf) = @_;
829
830 my $rrd = "${rrd_dir}/$rrdname";
831
832 my $setup = {
833 hour => [ 60, 70 ],
834 day => [ 60*30, 70 ],
835 week => [ 60*180, 70 ],
836 month => [ 60*720, 70 ],
837 year => [ 60*10080, 70 ],
838 };
839
840 my ($reso, $count) = @{$setup->{$timeframe}};
841 my $ctime = $reso*int(time()/$reso);
842 my $req_start = $ctime - $reso*$count;
843
844 $cf = "AVERAGE" if !$cf;
845
846 my @args = (
847 "-s" => $req_start,
848 "-e" => $ctime - 1,
849 "-r" => $reso,
850 );
851
852 push @args, "--daemon" => "unix:${rrdcached_socket}"
853 if -S $rrdcached_socket;
854
855 my ($start, $step, $names, $data) = RRDs::fetch($rrd, $cf, @args);
856
857 my $err = RRDs::error;
858 die "RRD error: $err\n" if $err;
859
860 die "got wrong time resolution ($step != $reso)\n"
861 if $step != $reso;
862
863 my $res = [];
864 my $fields = scalar(@$names);
865 for my $line (@$data) {
866 my $entry = { 'time' => $start };
867 $start += $step;
868 for (my $i = 0; $i < $fields; $i++) {
869 my $name = $names->[$i];
870 if (defined(my $val = $line->[$i])) {
871 $entry->{$name} = $val;
872 } else {
873 # leave empty fields undefined
874 # maybe make this configurable?
875 }
876 }
877 push @$res, $entry;
878 }
879
880 return $res;
881}
882
8da6f9ec
DM
883sub decode_to_html {
884 my ($charset, $data) = @_;
885
886 my $res = $data;
887
888 eval { $res = encode_entities(decode($charset, $data)); };
889
890 return $res;
891}
892
46f9e9af
DM
893sub decode_rfc1522 {
894 my ($enc) = @_;
895
896 my $res = '';
897
898 return '' if !$enc;
899
900 eval {
901 foreach my $r (MIME::Words::decode_mimewords($enc)) {
902 my ($d, $cs) = @$r;
903 if ($d) {
904 if ($cs) {
905 $res .= decode($cs, $d);
906 } else {
907 $res .= $d;
908 }
909 }
910 }
911 };
912
913 $res = $enc if $@;
914
915 return $res;
916}
917
9a56f771
DM
918sub rfc1522_to_html {
919 my ($enc) = @_;
920
921 my $res = '';
922
923 return '' if !$enc;
924
925 eval {
926 foreach my $r (MIME::Words::decode_mimewords($enc)) {
927 my ($d, $cs) = @$r;
928 if ($d) {
929 if ($cs) {
930 $res .= encode_entities(decode($cs, $d));
931 } else {
932 $res .= encode_entities($d);
933 }
934 }
935 }
936 };
937
938 $res = $enc if $@;
939
940 return $res;
941}
942
9d26ab13
DM
943# RFC 2047 B-ENCODING http://rfc.net/rfc2047.html
944# (Q-Encoding is complex and error prone)
945sub bencode_header {
946 my $txt = shift;
947
948 my $CRLF = "\015\012";
949
950 # Nonprintables (controls + x7F + 8bit):
951 my $NONPRINT = "\\x00-\\x1F\\x7F-\\xFF";
952
953 # always use utf-8 (work with japanese character sets)
954 $txt = encode("UTF-8", $txt);
955
956 return $txt if $txt !~ /[$NONPRINT]/o;
957
958 my $res = '';
959
960 while ($txt =~ s/^(.{1,42})//sm) {
961 my $t = MIME::Words::encode_mimeword ($1, 'B', 'UTF-8');
962 $res .= $res ? "\015\012\t$t" : $t;
963 }
964
965 return $res;
966}
967
7d89adf4 968sub load_sa_descriptions {
e325aa6f 969 my ($additional_dirs) = @_;
7d89adf4
DM
970
971 my @dirs = ('/usr/share/spamassassin',
972 '/usr/share/spamassassin-extra');
973
e325aa6f
DC
974 push @dirs, @$additional_dirs if @$additional_dirs;
975
7d89adf4
DM
976 my $res = {};
977
978 my $parse_sa_file = sub {
979 my ($file) = @_;
980
981 open(my $fh,'<', $file);
982 return if !defined($fh);
983
984 while (defined(my $line = <$fh>)) {
985 if ($line =~ m/^describe\s+(\S+)\s+(.*)\s*$/) {
986 my ($name, $desc) = ($1, $2);
987 next if $res->{$name};
988 $res->{$name}->{desc} = $desc;
989 if ($desc =~ m|[\(\s](http:\/\/\S+\.[^\s\.\)]+\.[^\s\.\)]+)|i) {
990 $res->{$name}->{url} = $1;
991 }
992 }
993 }
994 close($fh);
995 };
996
997 foreach my $dir (@dirs) {
998 foreach my $file (<$dir/*.cf>) {
999 $parse_sa_file->($file);
1000 }
1001 }
1002
cda67dee 1003 $res->{'ClamAVHeuristics'}->{desc} = "ClamAV heuristic tests";
0d5209bf 1004
7d89adf4
DM
1005 return $res;
1006}
1007
8162c745
DM
1008sub format_uptime {
1009 my ($uptime) = @_;
1010
1011 my $days = int($uptime/86400);
1012 $uptime -= $days*86400;
1013
1014 my $hours = int($uptime/3600);
1015 $uptime -= $hours*3600;
1016
1017 my $mins = $uptime/60;
1018
1019 if ($days) {
1020 my $ds = $days > 1 ? 'days' : 'day';
1021 return sprintf "%d $ds %02d:%02d", $days, $hours, $mins;
1022 } else {
1023 return sprintf "%02d:%02d", $hours, $mins;
1024 }
1025}
1026
3dfe317a
DM
1027sub finalize_report {
1028 my ($tt, $template, $data, $mailfrom, $receiver, $debug) = @_;
1029
1030 my $html = '';
1031
1032 $tt->process($template, $data, \$html) ||
1033 die $tt->error() . "\n";
1034
1035 my $title;
1036 if ($html =~ m|^\s*<title>(.*)</title>|m) {
1037 $title = $1;
1038 } else {
1039 die "unable to extract template title\n";
1040 }
1041
1042 my $top = MIME::Entity->build(
1043 Type => "multipart/related",
1044 To => $data->{pmail},
1045 From => $mailfrom,
1046 Subject => bencode_header(decode_entities($title)));
1047
1048 $top->attach(
1049 Data => $html,
1050 Type => "text/html",
1051 Encoding => $debug ? 'binary' : 'quoted-printable');
1052
1053 if ($debug) {
1054 $top->print();
1055 return;
1056 }
1057 # we use an empty envelope sender (we dont want to receive NDRs)
1058 PMG::Utils::reinject_mail ($top, '', [$receiver], undef, $data->{fqdn});
1059}
1060
2f7031b7
DM
1061sub lookup_timespan {
1062 my ($timespan) = @_;
1063
1064 my (undef, undef, undef, $mday, $mon, $year) = localtime(time());
1065 my $daystart = timelocal(0, 0, 0, $mday, $mon, $year);
1066
1067 my $start;
1068 my $end;
1069
1070 if ($timespan eq 'today') {
1071 $start = $daystart;
1072 $end = $start + 86400;
1073 } elsif ($timespan eq 'yesterday') {
1074 $end = $daystart;
1075 $start = $end - 86400;
1076 } elsif ($timespan eq 'week') {
1077 $end = $daystart;
1078 $start = $end - 7*86400;
1079 } else {
1080 die "internal error";
1081 }
1082
1083 return ($start, $end);
1084}
1085
17a7c6c9
DM
1086my $rbl_scan_last_cursor;
1087my $rbl_scan_start_time = time();
1088
1089sub scan_journal_for_rbl_rejects {
1090
1091 # example postscreen log entry for RBL rejects
1092 # 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>
1093
2e0e3415
DM
1094 # example for PREGREET reject
1095 # Dec 7 06:57:11 proxmox postfix/postscreen[32084]: PREGREET 14 after 0.23 from [x.x.x.x]:63492: EHLO yyyyy\r\n
1096
17a7c6c9
DM
1097 my $identifier = 'postfix/postscreen';
1098
2e0e3415
DM
1099 my $rbl_count = 0;
1100 my $pregreet_count = 0;
17a7c6c9
DM
1101
1102 my $parser = sub {
1103 my $line = shift;
1104
1105 if ($line =~ m/^--\scursor:\s(\S+)$/) {
1106 $rbl_scan_last_cursor = $1;
1107 return;
1108 }
1109
2e0e3415
DM
1110 if ($line =~ m/\s$identifier\[\d+\]:\sNOQUEUE:\sreject:.*550 5.7.1 Service unavailable;/) {
1111 $rbl_count++;
1112 } elsif ($line =~ m/\s$identifier\[\d+\]:\sPREGREET\s\d+\safter\s/) {
1113 $pregreet_count++;
1114 }
17a7c6c9
DM
1115 };
1116
1117 # limit to last 5000 lines to avoid long delays
1118 my $cmd = ['journalctl', '--show-cursor', '-o', 'short-unix', '--no-pager',
1119 '--identifier', $identifier, '-n', 5000];
1120
1121 if (defined($rbl_scan_last_cursor)) {
1122 push @$cmd, "--after-cursor=${rbl_scan_last_cursor}";
1123 } else {
1124 push @$cmd, "--since=@" . $rbl_scan_start_time;
1125 }
1126
1127 PVE::Tools::run_command($cmd, outfunc => $parser);
1128
2e0e3415 1129 return ($rbl_count, $pregreet_count);
17a7c6c9
DM
1130}
1131
5d5af7c5
DM
1132my $hwaddress;
1133
1134sub get_hwaddress {
1135
1136 return $hwaddress if defined ($hwaddress);
1137
1138 my $fn = '/etc/ssh/ssh_host_rsa_key.pub';
1139 my $sshkey = PVE::Tools::file_get_contents($fn);
1140 $hwaddress = uc(Digest::MD5::md5_hex($sshkey));
1141
1142 return $hwaddress;
1143}
1144
75ce5866
DM
1145my $default_locale = "en_US.UTF-8 UTF-8";
1146
1147sub cond_add_default_locale {
1148
1149 my $filename = "/etc/locale.gen";
1150
1151 open(my $infh, "<", $filename) || return;
1152
1153 while (defined(my $line = <$infh>)) {
1154 if ($line =~ m/^\Q${default_locale}\E/) {
1155 # already configured
1156 return;
1157 }
1158 }
1159
1160 seek($infh, 0, 0) // return; # seek failed
1161
1162 open(my $outfh, ">", "$filename.tmp") || return;
1163
1164 my $done;
1165 while (defined(my $line = <$infh>)) {
1166 if ($line =~ m/^#\s*\Q${default_locale}\E.*/) {
1167 print $outfh "${default_locale}\n" if !$done;
1168 $done = 1;
1169 } else {
1170 print $outfh $line;
1171 }
1172 }
1173
1174 print STDERR "generation pmg default locale\n";
1175
1176 rename("$filename.tmp", $filename) || return; # rename failed
1177
1178 system("dpkg-reconfigure locales -f noninteractive");
1179}
1180
758c7b6b 11811;