package tinyfirewall; use diagnostics; use strict; use commands; use run_program; use network::netconnect; use network; use POSIX qw(tmpnam); use MDK::Common; my @messages = (_("tinyfirewall configurator This configures a personal firewall for this Mandrake Linux machine. For a powerful dedicated firewall solution, please look to the specialized MandrakeSecurity Firewall distribution."), _("We'll now ask you questions about which services you'd like to allow the Internet to connect to. Please think carefully about these questions, as your computer's security is important. Please, if you're not currently using one of these services, firewall it off. You can change this configuration anytime you like by re-running this application!"), _("Are you running a web server on this machine that you need the whole Internet to see? If you are running a webserver that only needs to be accessed by this machine, you can safely answer NO here. "), _("Are you running a name server on this machine? If you didn't set one up to give away IP and zone information to the whole Internet, please answer no. "), _("Do you want to allow incoming Secure Shell (ssh) connections? This is a telnet-replacement that you might use to login. If you're using telnet now, you should definitely switch to ssh. telnet is not encrypted -- so some attackers can steal your password if you use it. ssh is encrypted and doesn't allow for this eavesdropping."), _("Do you want to allow incoming telnet connections? This is horribly unsafe, as we explained in the previous screen. We strongly recommend answering No here and using ssh in place of telnet. "), _("Are you running an FTP server here that you need accessible to the Internet? If you are, we strongly recommend that you only use it for Anonymous transfers. Any passwords sent by FTP can be stolen by some attackers, since FTP also uses no encryption for transferring passwords. "), _("Are you running a mail server here? If you're sending you messages through pine, mutt or any other text-based mail client, you probably are. Otherwise, you should firewall this off. "), _("Are you running a POP or IMAP server here? This would be used to host non-web-based mail accounts for people via this machine. "), _("You appear to be running a 2.2 kernel. If your network IP is automatically set by a computer in your home or office (dynamically assigned), we need to allow for this. Is this the case? "), _("Is your computer getting time syncronized to another computer? Mostly, this is used by medium-large Unix/Linux organizations to synchronize time for logging and such. If you're not part of a larger office and haven't heard of this, you probably aren't."), _("Configuration complete. May we write these changes to disk? ") ); my %settings; my $config_file = "/etc/Bastille/bastille-firewall.cfg"; my $default_config_file = "/usr/share/Bastille/bastille-firewall.cfg"; # set this later sub ReadConfig { -e $config_file or commands::cp($default_config_file, $config_file); add2hash(\%settings, { getVarsFromSh("$config_file") }); } sub SaveConfig { my $tmp_file = tmpnam(); open CONFIGFILE, "$config_file" or die _("Can't open %s: %s\n", $config_file, $!); open TMPFILE, ">$tmp_file" or die _("Can't open %s for writing: %s\n", $tmp_file, $!); while (my $line = ) { if ($line =~ m/^(.+)\s*\=\s*\"(.*)\"/) { my ($variable, $value) = ($1, $2); my $newvalue = $settings{$variable}; $line =~ s/\".*\"/\"$newvalue\"/ if (exists $settings{$variable}); } print TMPFILE $line; } close CONFIGFILE; close TMPFILE; rename ($config_file, $config_file . ".orig"); system ("/bin/cp $tmp_file $config_file"); system ("/bin/rm $tmp_file"); } sub DoInterface { my ($in)=@_; $::isWizard=1; my $GetNetworkInfo = sub { $settings{DNS_SERVERS} = join(' ', uniq(split(' ', $settings{DNS_SERVERS}), @{network::read_resolv_conf("/etc/resolv.conf")}{'dnsServer', 'dnsServer2', 'dnsServer3'})); my (undef, undef, @netstat) = `/bin/netstat -in`; my @interfaces = map { /(\S+)/ } @netstat; my (@route, undef, undef) = `/sbin/route -n`; my $defaultgw; my $iface; foreach (@route) { my @parts = split /\s+/; $parts[0] eq "0.0.0.0" and $defaultgw = $parts[1], $iface = $parts[7] } my $fulliface = $iface; $fulliface =~ s/[0-9]+/\\\+/; $settings{PUBLIC_INTERFACES} = join(' ', uniq(split(' ', $settings{PUBLIC_INTERFACES}), $iface)); $settings{PUBLIC_INTERFACES} =~ $fulliface and $settings{PUBLIC_INTERFACES} =~ s/$iface *//; $settings{INTERNAL_IFACES} = join(' ', uniq(split(' ', $settings{INTERNAL_IFACES}), map { my $i=$_; my $f=$i; $f=~s/[0-9]+/\\\+/; if_(and_( map {$settings{$_} !~ /$i/ and $settings{$_} !~ /$f/ } ('TRUSTED_IFACES', 'PUBLIC_IFACES', 'INTERNAL_IFACES')), $i) } @interfaces )); }; # my $popimap = sub { $_[0] or return; $settings{FORCE_PASV_FTP} = 11; mapn {$settings{"$_[0]"} = "$_[1]"; } #[ qw(FORCE_PASV_FTP TCP_BLOCKED_SERVICES UDP_BLOCKED_SERVICES ICMP_ALLOWED_TYPES ENABLE_SRC_ADDR_VERIFY IP_MASQ_NETWORK IP_MASQ_MODULES REJECT_METHOD) ] , #[ "N", "6000:6020", "2049", "destination-unreachable echo-reply time-exceeded" , "Y", "", "", "DENY" ]; }; my $popimap = sub { $_[0] or return; $settings{'FORCE_PASV_FTP'} = "N"; $settings{TCP_BLOCKED_SERVICES}= "6000:6020"; $settings{UDP_BLOCKED_SERVICES}= "2049"; $settings{ICMP_ALLOWED_TYPES}= "destination-unreachable echo-reply time-exceeded"; $settings{ENABLE_SRC_ADDR_VEIFY}= "Y"; $settings{IP_MASQ_NETWORK}= ""; $settings{IP_MASQ_MODULES}= ""; $settings{REJECT_METHOD}= "DENY"; }; # my $ntp = sub { $_[0] or return; mapn { $settings{$_[0]} = $_[1] } ['ICMP_OUTBOUND_DISABLED_TYPES}', 'LOG_FAILURES'], [ "", "N"] }; my $ntp = sub { $_[0] or return; $settings{'ICMP_OUTBOUND_DISABLED_TYPES}'} = ""; $settings{'LOG_FAILURES'} = "N"; }; my $dhcp = sub { if ($_[0]) { $settings{DHCP_IFACES} and return; my (undef, undef, @netstat) = `/bin/netstat -in`; $settings{DHCP_IFACES} = join(' ', split(' ', $settings{DHCP_IFACES}), map { /(\S+)/ } @netstat ); } else { $settings{DHCP_IFACES} = "" } }; my $quit = sub { $_[0] or $in->exit(0); SaveConfig(); system($_) foreach ("/bin/cp /usr/share/Bastille/bastille-ipchains /usr/share/Bastille/bastille-netfilter /sbin", "/bin/cp /usr/share/Bastille/bastille-firewall /etc/rc.d/init.d/", "/bin/chmod 0700 /etc/rc.d/init.d/bastille-firewall", "/bin/chmod 0700 /sbin/bastille-ipchains", "/bin/chmod 0700 /sbin/bastille-netfilter", "/sbin/chkconfig bastille-firewall on", "/etc/rc.d/init.d/bastille-firewall stop", "/etc/rc.d/init.d/bastille-firewall start"); $in->exit(0); return; $_[0] or $in->exit(0); commands::cp("-f", $config_file, $config_file . ".orig"); substInFile { if(/^(.+)\s*\=/) { $a=$settings{$1}; s/\".*\"/\"$a\"/; } } $config_file; system($_) foreach ("/bin/cp /usr/share/Bastille/bastille-ipchains /usr/share/Bastille/bastille-netfilter /sbin", "/bin/cp /usr/share/Bastille/bastille-firewall /etc/rc.d/init.d/", "/bin/chmod 0700 /etc/rc.d/init.d/bastille-firewall", "/bin/chmod 0700 /sbin/bastille-ipchains", "/bin/chmod 0700 /sbin/bastille-netfilter", "/sbin/chkconfig bastille-firewall on", "/etc/rc.d/init.d/bastille-firewall stop", "/etc/rc.d/init.d/bastille-firewall start"); }; my @struct = ( [$GetNetworkInfo], [], [undef , undef, undef, undef, ["tcp", "80"], ["tcp", "443"]], [undef , undef, undef, undef, ["tcp", "53"], ["udp", "53"]], [undef , undef, undef, undef, ["tcp", "22"]], [undef , undef, undef, undef, ["tcp", "23"]], [undef , undef, undef, undef, ["tcp", "20"],["tcp", "21"]], [undef , undef, undef, undef, ["tcp", "25"]], [undef , undef, undef, $popimap, ["tcp", "109"], ["tcp", "110"], ["tcp", "143"]], [undef , _("No I don't need DHCP"), _("Yes I need DHCP"), $dhcp], [undef , _("No I don't need NTP"), _("Yes I need NTP"), $ntp ], [undef , _("Don't Save"), _("Save & Quit"), $quit ] ); if (!Kernel22()) { pop @struct; pop @struct; pop @struct; @struct = ( @struct, [undef , _("Don't Save"), _("Save & Quit"), $quit ] ); $messages[9]=$messages[11]; } for (my $i=0;$i<@struct;$i++) { $::Wizard_no_previous = $i == 0; $::Wizard_finished = $i == $#struct; my $l = $struct[$i]; @$l or goto ask; if (@$l == 1) { ($l->[0])->(); ask: $in->ask_okcancel(_("Firewall Configuration Wizard"), $messages[$i],1) ? next : goto prev; } my $no = $l->[1] ? $l->[1] : _("No (firewall this off from the internet)"); my $yes = $l->[2] ? $l->[2] : _("Yes (allow this through the firewall)"); if (my $e = $in->ask_from_list_(_("Firewall Configuration Wizard"), $messages[$i], [ $yes, $no ], or_( map { $_ && CheckService($_->[0], $_->[1]) } (@$l[4..6])) ? $yes : $no )) { map { $_ and Service($e=~/Yes/, $_->[0], $_->[1]) } (@{$struct[$i]}[4..6]); $struct[$i][3] and $struct[$i][3]->($e=~/Yes/ || $e eq _("Save & Quit")); } else { prev: $i = $i-2 >= -1 ? $i-2 : -1; } } } sub unbox_service { split ' ', $settings{uc($_[0]) . "_PUBLIC_SERVICES"} } sub Service { my ($add, $protocol, $port) = @_; my @l = unbox_service($protocol); @l = uniq($add ? (@l, $port) : grep { $_ ne $port } @l); $settings{uc($protocol) . "_PUBLIC_SERVICES"} = join(' ', @l); } sub CheckService { member($_[1], unbox_service($_[0])); } sub Kernel22 { my ($major, $minor, $patchlevel) = (cat_("/proc/version"))[0] =~ m/^Linux version ([0-9]+)\.([0-9]+)\.([0-9]+)/; $major eq "2" && $minor eq "2"; } sub main { my ($in)=@_; my $dialog = new Gtk::Dialog(); $dialog->set_position(1); $dialog->vbox->set_border_width(10); my $label = new Gtk::Label(_("Please Wait... Verifying installed packages")); $dialog->signal_connect ( delete_event => sub { Gtk->main_quit(); }); $dialog->vbox->pack_start($label,1,1,20); $dialog->show_all; Gtk->main_iteration while Gtk->events_pending; if (!$in->do_pkgs->install(Kernel22() ? "ipchains" : "iptables", "Bastille")) { $in->ask_warn('', _("Failure installing the needed packages : %s and Bastille. Try to install them manually.", Kernel22() ? "ipchains" : "iptables") ); $dialog->destroy; $in->exit(0); } ReadConfig; DoInterface($in); } ='#n203'>203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
package MGA::Advisories;

use warnings;
use strict;
use YAML qw(LoadFile DumpFile Load);
use Template;
use DateTime;
use Email::Sender::Simple qw(try_to_sendmail);
use Email::Simple;
use Email::Simple::Creator;
use HTTP::Request;
use LWP::UserAgent;
use File::Basename;
use XMLRPC::Lite;
use Term::ReadKey;
#use Data::Dump qw(dd);

our $config_file = '/usr/share/mga-advisories/config';
our $config = LoadFile($ENV{MGAADV_CONF} || $config_file);
our $home_config_file = $ENV{HOME} . '/.mga-advisories/mga-advisories.conf';
my $custom_config_file = -f $home_config_file ? $home_config_file
        : '/etc/mga-advisories.conf';
my $custom_config = LoadFile($custom_config_file);
foreach my $k (keys %$custom_config) {
    $config->{$k} = $custom_config->{$k};
}

my %basename = (
    CVE => sub { $_[0] },
    ID  => sub { $_[0] },
    rel => sub { $_[0] },
    src => sub { 'src_' . $_[0] },
);

my %tools = (
    pkgname => sub { $_[0] =~ m/(.+)-[^-]+-[^-]+/; $1; },
);

my %bz = (
    proxy => undef,
    token => undef
);

my @report_logs;
sub report_log {
    push @report_logs, @_;
}

sub report_exit {
    report_log($_[0]);
    send_report({ error => $_[0] });
    exit 1;
}

sub status_file {
    $config->{status_dir} . '/' . $_[0];
}

sub save_status {
    my ($advdb, $adv) = @_;
    return if $advdb->{advisories}{$adv}{no_save_status};
    my $statusfile = status_file($adv);
    DumpFile($statusfile, $advdb->{advisories}{$adv}{status});
}

sub init_bz {
    return 1 if ($bz{proxy});
    return 0 if (!$config->{bugzilla_url});

    $bz{proxy} = XMLRPC::Lite->proxy(
        $config->{bugzilla_url} . "xmlrpc.cgi"
    );
    if ($config->{bugzilla_tokenfile} && -f glob($config->{bugzilla_tokenfile})) {
        if (open(my $fh, '<', glob($config->{bugzilla_tokenfile}))) {
            while (my $row = <$fh>) {
                chomp($bz{token} = $row);
                last;
            }
            close $fh;
        }
    }

    #$bz{proxy}->import(+trace => 'debug');

    return 1;
}

sub call_bz {
    my ($method, @args) = @_;

    return 0 if (!init_bz());

    $args[0]->{token} = $bz{token} if ($bz{token});

    my $soapresult = $bz{proxy}->call($method, @args);
    if ($soapresult->fault) {
        if ($soapresult->faultcode == 410) {
            # We need to login
            if (login_bz()) {
                $args[0]->{token} = $bz{token};

                # Try the call again now we're logged in.
                $soapresult = $bz{proxy}->call($method, @args);
                return $soapresult->result unless $soapresult->fault;
            }
        }

        my ($package, $filename, $line) = caller;
        report_log(
            $soapresult->faultcode . ' ' . $soapresult->faultstring .
            " in SOAP call near $filename line $line."
        );
        return 0;
    }
    return $soapresult->result;
}

sub login_bz {
    my ($login, $password);
    if ($config->{bugzilla_login} && $config->{bugzilla_password}) {
        $login = $config->{bugzilla_login};
        $password = $config->{bugzilla_password};
    } elsif ($config->{mode} eq 'qa') {
        print "Please enter your bugzilla user name (email address): ";
        chomp($login = <STDIN>);
        print "Please now enter your bugzilla password: ";
        ReadMode('noecho');
        chomp($password = <STDIN>);
        ReadMode(0);        # back to normal
        print "\n";
    }

    if ($login && $password) {
        if ( $password =~ /^file:\/\// ) {
            if (open(my $fh, '<:encoding(UTF-8)', substr $password, 7)) {
                while (my $row = <$fh>) {
                    chomp($password = $row);
                    last;
                }
                close $fh;
            } else {
                print STDERR "Warning: Cannot open bugzilla password file\n";
                return 0;
            }
        }
        my $soapresult = $bz{proxy}->call(
            'User.login',
            {
                login => $login,
                password => $password,
                remember => 1
            }
        );
        if ($soapresult->result && $soapresult->result->{token}) {
            $bz{token} = $soapresult->result->{token};
            if ($config->{bugzilla_tokenfile}) {
                if (open(my $fh, '>', glob($config->{bugzilla_tokenfile}))) {
                    print $fh $bz{token};
                    close $fh;
                    chmod 0600, glob($config->{bugzilla_tokenfile});
                }
            }
        }
        return 1 unless $soapresult->fault;
    }
    return 0;
}


sub get_advisories_from_dir {
    my %advisories;
    foreach my $advfile (glob "$config->{advisories_dir}/*.adv") {
        my $adv = LoadFile($advfile);
        if (!$adv->{ID}) {
            next unless $config->{mode} eq 'qa';
            $adv->{ref} = basename($advfile, ".adv");
            $adv->{ID} = next_id('TODO', keys %advisories);
            $adv->{no_save_status} = 1;
        }
        report_exit("Duplicate advisory $adv->{ID}") if $advisories{$adv->{ID}};
        report_exit("Unknown type $adv->{type}") unless
                $config->{advisory_types}{$adv->{type}};
        $advisories{$adv->{ID}} = $adv;
        my $statusfile = status_file($adv->{ID});
        $adv->{status} = -f $statusfile ? LoadFile($statusfile) : {};
    }
    return \%advisories;
}

sub next_id {
    my $prefix = shift;
    my $year = DateTime->now->year;
    my @used_ids = map { m/^$prefix-$year-(\d+)$/ ? int $1 : () } @_;
    my $newid = (0, sort { $a <=> $b } @used_ids)[-1] + 1;
    return sprintf("%s-%s-%.4d", $prefix, $year, $newid);
}

sub assign_id {
    my ($advname) = @_;
    my $advfile = "$config->{advisories_dir}/$advname.adv";
    $advfile =~ s/\.adv\.adv$/.adv/;

    if ( ! -f $advfile ) {
        print STDERR "Cannot find advisory file '$advname'\n";
        return;
    }

    my $exitstatus = system("svn status -q $advfile | grep -q ^M");
    if ( 0 == $exitstatus ) {
        print STDERR "$advname appears to be modified. Please commit it first.\n";
        return;
    }

    my $adv = LoadFile($advfile);
    if ($adv->{ID}) {
        print STDERR "$advname already has an ID assigned: $adv->{ID}\n";
        return;
    }
    my $type = $config->{advisory_types}{$adv->{type}}{prefix};
    if (!$type) {
        print STDERR "Unknown type $adv->{type}\n";
        return;
    }

    # Turn on autoflush
    $|++;

    if (!init_bz()) {
        print STDERR "Warning: Cannot check bugzilla. Please double check manually\n";
    } else {
        # Advisories are not always just [0-9]+.adv, but are
        # sometimes [0-9]+.mga3.adv etc. so extract the real bug number
        (my $advbugnum) = $advname =~ m/^([0-9]+)/g;

        if (scalar($adv->{references}) < 1) {
            print STDERR "No reference links found in advisory\n";
            return;
        }
        (my $bugnum) = $adv->{references}[0] =~ m/$config->{bugzilla_url}.*=([0-9]+)$/g;
        if (!defined $bugnum) {
            print STDERR "First reference does not appear to be a Mageia bug link\n";
            return;
        }
        if ($advbugnum ne $bugnum) {
            print STDERR "First reference is not the corresponding Mageia advisory bug ($advbugnum != $bugnum)\n";
            return;
        }

        if (my $result = call_bz('Bug.get', {ids => [$bugnum]})) {
            my $failed = 0;
            my $bug = $result->{bugs}->[0];
            print "Found Bug: " . $bug->{summary} . "\n";

            my ($buffer, $msg);
            print $msg = sprintf("%-40s", "Checking for QA validation keyword… ");
            $buffer = $msg;
            my $found_keyword = 0;
            if (scalar($bug->{keywords}) > 0) {
                my $keywords = $bug->{keywords};
                foreach my $keyword (@$keywords) {
                    if ('validated_update' eq $keyword) {
                        $found_keyword = 1;
                        last;
                    }
                }
            }
            if ($found_keyword) {
                print $msg = "✔\n";
            } else {
                print $msg = "✘\n";
                $failed = 1;
            }
            $buffer .= $msg;

            my $depsfailed = 0;
            print $msg = sprintf("%-40s", "Checking dependent bugs… ");
            $buffer .= $msg;
            my $depends = $bug->{depends_on};
            if (scalar(@$depends) < 1) {
                print $msg = "✔ (None found)\n";
                $buffer .= $msg;
            } else {
                my $first = 1;
                foreach my $dependent_bug_num (@$depends) {
                    if (!$first) {
                        print $msg = ', ';
                        $buffer .= $msg;
                    }
                    $first = 0;

                    if ($result = call_bz('Bug.get', {ids => [$dependent_bug_num]})) {
                        my $blocking_bug = $result->{bugs}->[0];

                        if ($blocking_bug->{is_open}) {
                            print $msg = "✘ $dependent_bug_num";
                            $depsfailed = 1;
                        } else {
                            print $msg = "✔ $dependent_bug_num";
                        }
                    } else {
                        print "? $dependent_bug_num\n";
                        print STDERR "Error: There was a problem communicating with bugzilla for bug $dependent_bug_num\n";
                        return;
                    }
                    $buffer .= $msg;
                }
                print $msg = "\n";
                $buffer .= $msg;
            }


            if (!$failed && $depsfailed) {
                ReadMode 4; # Turn off controls keys
                print $msg = "Dependent bug! Publish anyway? [y/N]: ";
                $buffer .= $msg;
                my $key = 'x';
                while ( $key ne "\n" && $key ne "y" && $key ne "Y" && $key ne "n" && $key ne "N" ) {
                    $key = ReadKey(0);
                }
                ReadMode 0; # Reset tty mode before exiting
                if ( $key eq "\n" || $key eq "n" || $key eq "N" ) {
                    $failed = 1;
                    print $msg = " ✘\n";
                } else {
                    print $msg = " ✔\n";
                }
                $buffer .= $msg;
            }

            print $msg = sprintf("%-40s", "Checking SRPMs… ");
            $buffer .= $msg;
            my $ua = LWP::UserAgent->new;
            $ua->max_redirect(0);
            foreach my $rel (keys %{$adv->{src}}) {
                foreach my $media (keys %{$adv->{src}{$rel}}) {
                    foreach my $srpm (@{$adv->{src}{$rel}{$media}}) {
                        my $req = HTTP::Request->new(GET => "http://repository.mageia.org/qa/checksrpm/update/$rel/$media/$srpm");
                        my $resp = $ua->request($req);

                        if ($resp->code eq 302 && $resp->header('Location') =~ /\/qa\/checksrpm\/found$/) {
                            print $msg = "✔ ";
                        } else {
                            print $msg = "✘ ($rel/$media/$srpm) ";
                            $failed = 1;
                        }
                        $buffer .= $msg;
                    }
                }
            }
            print $msg = "\n";
            $buffer .= $msg;

            if ($failed) {
                print STDERR "Error: Cross check failed.\n";
                return;
            }
        } else {
            print STDERR "Warning: Cannot check bugzilla. Please double check manually\n";
        }
    }

    # TODO: Check SRPMs really exist in the media

    printf "%-40s", "Assigning ID to advisory $advname… ";
    $adv->{ID} = next_id($type, keys %{get_advisories_from_dir()});
    open(my $fh, '>>', $advfile) or die "Error opening $advfile";
    print $fh "ID: $adv->{ID}\n";
    close $fh;
    print "✔ $adv->{ID}\n";


    ReadMode 4; # Turn off controls keys
    print "Do you want to publish now? [Y/n]: ";
    my $key = 'x';
    while ( $key ne "\n" && $key ne "y" && $key ne "Y" && $key ne "n" && $key ne "N" ) {
        $key = ReadKey(0);
    }
    ReadMode 0; # Reset tty mode before exiting
    if ( $key ne "\n" && $key ne "y" && $key ne "Y" ) {
        print "$key\n";
        return;
    }
    print "   ✔\n";

    printf "%-40s", "Publishing advisory $adv->{ID}… ";
    my $message = $adv->{ID};
    my @pkgs;
    foreach my $rel (keys %{$adv->{src}}) {
        foreach my $media (keys %{$adv->{src}{$rel}}) {
            foreach my $srpm (@{$adv->{src}{$rel}{$media}}) {
                push @pkgs, $srpm;
            }
        }
    }
    $message .= ': '.join(', ', @pkgs);
    $exitstatus = system(('svn', 'commit', '-q',  '-m', $message, $advfile));
    if (0 == $exitstatus) {
        print "✔\n";
    } else {
        print "✘\n";
    }
}

sub assign_ids {
    # Ensure users local repo is up to date
    my $exitstatus = system("svn up");
    if ( 0 != $exitstatus ) {
        print STDERR "Subversion update appears to have failed.\n";
        return;
    }

    my %advdb;
    $advdb{advisories} = get_advisories_from_dir();
    sort_advisories(\%advdb);
    output_pages();

    # We will have exited by now in the event of e.g. a Yaml or processing error

    foreach my $advfile (glob "$config->{advisories_dir}/*.adv") {
        my $adv = LoadFile($advfile);
        next if ($adv->{ID});
        assign_id(basename($advfile, ".adv"));
        print "\n";
    }
}

sub advdb_dumpfile {
    $config->{advdb_dumpfile} || $ENV{HOME} . '/.mga-advisories/advisories.yaml';
}

sub get_advisories_from_dump {
    my $advfile = advdb_dumpfile;
    return -f $advfile ? LoadFile($advfile) : {};
}

sub get_advisories {
    return $config->{mode} eq 'dump' ? get_advisories_from_dump
        : get_advisories_from_dir;
}

sub download_advisories {
    my $oldadvisories = get_advisories_from_dump;
    my $ua = LWP::UserAgent->new;
    my $resp = $ua->get($config->{dump_url});
    die "Error loading $config->{dump_url}" unless $resp->is_success;
    my $newadvisories = Load($resp->decoded_content);
    my @newadv = grep { ! $oldadvisories->{$_} } keys %$newadvisories;
    if (@newadv) {
        my %n;
        my @v = @{$newadvisories}{@newadv};
        @n{@newadv} = @v;
        print "New advisories have been downloaded :\n";
        listadv({advisories => \%n});
    } else {
        print "No new advisories available\n";
    }
    if (!-d dirname(advdb_dumpfile)) {
        mkdir dirname(advdb_dumpfile)
                || die "Error creating directory " . dirname(advdb_dumpfile);
    }
    open(my $fh, '>', advdb_dumpfile)
        || die "Could not open " . advdb_dumpfile;
    print $fh $resp->decoded_content;
    close $fh;
}

sub move_packages {
    my ($advdb) = @_;
    return unless $config->{mode} eq 'site';
    return unless $config->{move_pkg_cmd};
    my @cmd = (
        $config->{move_pkg_cmd},
        '--sync',
        '--no-confirm'
    );
    foreach my $adv (keys %{$advdb->{advisories}}) {
        next if $advdb->{advisories}{$adv}{status}{moved};
        foreach my $rel (keys %{$advdb->{advisories}{$adv}{src}}) {
            foreach my $media (keys %{$advdb->{advisories}{$adv}{src}{$rel}}) {
                foreach my $srpm (@{$advdb->{advisories}{$adv}{src}{$rel}{$media}}) {
                    report_log("Moving package $srpm for $adv");
                    push(@cmd, "$rel/$media/$srpm.src.rpm");
                }
            }
        }
    }

    return if scalar(@cmd) < 4;
    report_exit("Could not move packages") if (0 != system(@cmd));

    foreach my $adv (keys %{$advdb->{advisories}}) {
        next if $advdb->{advisories}{$adv}{status}{moved};
        $advdb->{advisories}{$adv}{status}{moved} = time();
        save_status($advdb, $adv);
    }
}

sub publish_advisories {
    my ($advdb) = @_;
    foreach my $adv (sort keys %{$advdb->{advisories}}) {
        next if $advdb->{advisories}{$adv}{status}{published};
        $advdb->{advisories}{$adv}{status}{published} =
                $advdb->{advisories}{$adv}{pubtime} || time();
        save_status($advdb, $adv);
    }
}

sub adv_sort {
    my $advdb = shift;
    sort {
        my $now = time;
        my $pa = $advdb->{advisories}{$a}{status}{published} || $now;
        my $pb = $advdb->{advisories}{$b}{status}{published} || $now;
        return $pa == $pb ? $b cmp $a : $pb cmp $pa;
    } @_;
}

sub sort_advisories {
    my ($advdb) = @_;
    foreach my $adv (keys %{$advdb->{advisories}}) {
        push @{$advdb->{by_type}{$advdb->{advisories}{$adv}{type}}}, $adv;
        foreach my $cve (@{$advdb->{advisories}{$adv}{CVE}}) {
            push @{$advdb->{by_cve}{$cve}}, $adv;
        }
        foreach my $rel (keys %{$advdb->{advisories}{$adv}{src}}) {
            push @{$advdb->{by_rel}{$rel}}, $adv;
            foreach my $media (keys %{$advdb->{advisories}{$adv}{src}{$rel}}) {
                push @{$advdb->{by_media}{$media}}, $adv;
                foreach my $srpm (@{$advdb->{advisories}{$adv}{src}{$rel}{$media}}) {
                    my $pkgname = $tools{pkgname}->($srpm);
                    if ($pkgname) {
                        push @{$advdb->{by_src}{$pkgname}}, $adv
                            unless grep { $_ eq $adv } @{$advdb->{by_src}{$pkgname}};
                    } else {
                        print STDERR "Warning: Invalid SRPM '$srpm' for advisory '$adv'\n";
                    }
                }
            }
        }
    }
    foreach my $by ('by_type', 'by_cve', 'by_rel', 'by_media', 'by_src') {
        foreach my $k (keys %{$advdb->{$by}}) {
            $advdb->{$by}{$k} = [ adv_sort($advdb, @{$advdb->{$by}{$k}}) ];
        }
    }
    $advdb->{sorted} = [ adv_sort($advdb, keys %{$advdb->{advisories}}) ];
}

sub process_template {
    my ($template, $src, $vars, $dest, $ext) = @_;
    foreach my $extension ($ext ? $ext : @{$config->{output_format}}) {
        next unless -f "$config->{tmpl_dir}/$src.$extension";
        $template->process("$src.$extension", $vars,
                           ref $dest ? $dest : "$dest.$extension",
                           binmode => ':utf8')
                || die $template->error, "\n";
    }
}

sub output_pages {
    my ($advdb) = @_;
    my $template = Template->new(
        ENCODING     => 'utf8',
        INCLUDE_PATH => $config->{tmpl_dir},
        OUTPUT_PATH  => $config->{out_dir},
    );
    foreach my $adv (keys %{$advdb->{advisories}}) {
        my $vars = {
            config   => $config,
            advisory => $adv,
            advdb    => $advdb,
            basename => \%basename,
            tools    => \%tools,
        };
        process_template($template, 'advisory', $vars, $basename{ID}->($adv));
    }
    foreach my $by (['rel', 'by_rel'], ['CVE', 'by_cve'], ['src', 'by_src']) {
        foreach my $r (keys %{$advdb->{$by->[1]}}) {
            my $vars = {
                config   => $config,
                $by->[0] => $r,
                advdb    => $advdb,
                basename => \%basename,
                tools    => \%tools,
            };
            process_template($template, $by->[1], $vars, $basename{$by->[0]}->($r));
        }
    }
    my $vars = {
        config   => $config,
        advdb    => $advdb,
        basename => \%basename,
        tools    => \%tools,
    };
    process_template($template, 'index', $vars, 'index');
    process_template($template, 'advisories', $vars, 'advisories');
    process_template($template, 'infos', $vars, 'infos');
    process_template($template, 'CVE', $vars, 'CVE');
}

sub send_adv_mail {
    my ($advdb) = @_;
    return unless $config->{send_adv_mail} eq 'yes';
    return unless $config->{mode} eq 'site';
    my $template = Template->new(
        ENCODING     => 'utf8',
        INCLUDE_PATH => $config->{tmpl_dir},
    );
    foreach my $adv (sort keys %{$advdb->{advisories}}) {
        next if $advdb->{advisories}{$adv}{no_mail};
        next if $advdb->{advisories}{$adv}{no_save_status};
        next if $advdb->{advisories}{$adv}{status}{mail_sent};
        my $mailcontent;
        my $vars = {
            config   => $config,
            advisory => $adv,
            advdb    => $advdb,
            basename => \%basename,
            tools    => \%tools,
        };
        process_template($template, 'advisory', $vars, \$mailcontent, 'txt');
        my $email = Email::Simple->create(
            header => [
                To   => $config->{adv_mail_to},
                From => $config->{adv_mail_from},
                Subject => "$adv: " . $advdb->{advisories}{$adv}{subject},
            ],
            body   => $mailcontent
        );
        if (try_to_sendmail($email)) {
            report_log("Advisory mail for $adv sent");
            $advdb->{advisories}{$adv}{status}{mail_sent} = time();
            save_status($advdb, $adv);
            # Attempt to make the mail delivery "in order"
            sleep 1;
        } else {
            report_log("Error sending advisory mail $adv");
        }
    }
}

sub close_bugs {
    my ($advdb) = @_;
    return unless $config->{mode} eq 'site';

    if (!init_bz()) {
        report_log("Cannot close advisory bugs. Could not initialise bugzilla");
        return;
    }
    foreach my $adv (sort keys %{$advdb->{advisories}}) {
        next if $advdb->{advisories}{$adv}{status}{bug_closed};

        my $bugnum = 0;
        if (scalar($advdb->{advisories}{$adv}{references}) > 0) {
            ($bugnum) = $advdb->{advisories}{$adv}{references}[0] =~ m/$config->{bugzilla_url}.*=([0-9]+)$/g;
        }
        if (!$bugnum) {
            report_log("Could not extract bug number for $adv");
            next;
        }

        my $advurl = $config->{site_url} . '/' . $adv . '.html';
        my $comment = "An update for this issue has been pushed to Mageia Updates repository.\n\n$advurl";

        if (my $result = call_bz('Bug.update', { ids => [$bugnum], status => 'RESOLVED', resolution => 'FIXED', comment => { body => $comment } })) {
            report_log("Bug $bugnum closed for $adv");
            $advdb->{advisories}{$adv}{status}{bug_closed} = time();
            save_status($advdb, $adv);
        } else {
            report_log("Could not close bug $bugnum for $adv");
        }
    }
}

sub send_report {
    my ($advdb) = @_;
    return unless @report_logs;
    my $template = Template->new(
        ENCODING     => 'utf8',
        INCLUDE_PATH => $config->{tmpl_dir},
    );
    my $reportcontent;
    my $vars = {
        config      => $config,
        advdb       => $advdb,
        report_logs => \@report_logs,
    };
    process_template($template, 'report', $vars, \$reportcontent, 'txt');
    if ($config->{send_report_mail} eq 'yes' && $config->{mode} eq 'site') {
        my $email = Email::Simple->create(
            header => [