#!/usr/bin/perl
#=============================================================================
# Rotation of OpenID Connect keys
#
# This script is written to be used by cron to rotate keys.
#
# This is part of LemonLDAP::NG product, released under GPL
#=============================================================================

use strict;

use Lemonldap::NG::Common::Conf;
use Lemonldap::NG::Common::Util::Crypto;
use URI;

use Getopt::Long;
use Pod::Usage;

our $VERSION = "2.0.21";

# Options
my $opts = {};
my $help;
my $opt_user  = '__APACHEUSER__';
my $opt_group = '__APACHEGROUP__';

GetOptions(
    'help|h'         => \$help,
    'debug|d'         => \$opts->{debug},
) or pod2usage( -exitcode => 1, -verbose => 0 );

pod2usage(2) if $help;

eval {
    no warnings;
    POSIX::setgid( scalar( getgrnam($opt_group) ) );
    POSIX::setuid( scalar( getpwnam($opt_user) ) );
};

my $debug = $opts->{debug};

#=============================================================================
# Load configuration
#=============================================================================
my $lmconf = Lemonldap::NG::Common::Conf->new()
  or die $Lemonldap::NG::Common::Conf::msg;
my $conf = $lmconf->getConf();

my $cn = eval { URI->new( $conf->{portal} )->host } || 'localhost';
print "Configuration loaded\n" if $debug;

# Verify type
my $type = (
      $conf->{oidcServiceNewPrivateKeySig}
    ? $conf->{oidcServiceNewKeyTypeSig}
    : $conf->{oidcServiceKeyTypeSig}
  )
  || 'RSA';

die "Unknown key type $type" unless $type =~ /^(?:RSA|EC)$/;
print "Type is $type\n" if $debug;

#=============================================================================
# Generate new key
#=============================================================================
my $keys;

if ( $type eq 'EC' ) {
    $keys = Lemonldap::NG::Common::Util::Crypto::genEcKey('secp256r1');
}
else {
    $keys = Lemonldap::NG::Common::Util::Crypto::genCertKey( 2048, undef, $cn );
}

print "Private key generated:\n" . $keys->{private} . "\n" if $debug;
print "Public key generated:\n" . $keys->{public} . "\n"   if $debug;
print "Key ID generated: " . $keys->{hash} . "\n"          if $debug;

#=============================================================================
# Save configuration
#=============================================================================
$conf->{cfgAuthor} = 'Key rotation script';

if ( $conf->{oidcServiceNewKeyIdSig} and $conf->{oidcServiceNewPublicKeySig} ) {

    # Move current key into previous one
    $conf->{oidcServiceOldPrivateKeySig} = $conf->{oidcServicePrivateKeySig};
    $conf->{oidcServiceOldPublicKeySig}  = $conf->{oidcServicePublicKeySig};
    $conf->{oidcServiceOldKeyIdSig}      = $conf->{oidcServiceKeyIdSig};
    $conf->{oidcServiceOldKeyTypeSig}    = $conf->{oidcServiceKeyTypeSig};

    # Move next key into current one
    $conf->{oidcServicePrivateKeySig} = $conf->{oidcServiceNewPrivateKeySig};
    $conf->{oidcServicePublicKeySig}  = $conf->{oidcServiceNewPublicKeySig};
    $conf->{oidcServiceKeyIdSig}      = $conf->{oidcServiceNewKeyIdSig};
    $conf->{oidcServiceKeyTypeSig}    = $conf->{oidcServiceNewKeyTypeSig};
}
else {
    print STDERR
      "No previous pending new key found. Rotation will be done next time\n";
}

# Store new key
$conf->{oidcServiceNewPrivateKeySig} = $keys->{private};
$conf->{oidcServiceNewPublicKeySig}  = $keys->{public};
$conf->{oidcServiceNewKeyIdSig}      = $keys->{hash};
$conf->{oidcServiceNewKeyTypeSig}    = $type;

if ( $conf->{oidcServicePrivateKeyEnc} ) {
    $type = $conf->{oidcServiceKeyTypeEnc} || 'RSA';
    if ( $type eq 'EC' ) {
        $keys = Lemonldap::NG::Common::Util::Crypto::genEcKey('secp256r1');
    }
    else {
        $keys =
          Lemonldap::NG::Common::Util::Crypto::genCertKey( 2048, undef, $cn );
    }

    # Move current key into previous one
    $conf->{oidcServiceOldPrivateKeyEnc} = $conf->{oidcServicePrivateKeyEnc};
    $conf->{oidcServiceOldPublicKeyEnc}  = $conf->{oidcServicePublicKeyEnc};
    $conf->{oidcServiceOldKeyIdEnc}      = $conf->{oidcServiceKeyIdEnc};
    $conf->{oidcServiceOldKeyTypeEnc}    = $conf->{oidcServiceKeyTypeEnc};

    # Store new key
    $conf->{oidcServicePrivateKeyEnc} = $keys->{private};
    $conf->{oidcServicePublicKeyEnc}  = $keys->{public};
    $conf->{oidcServiceKeyIdEnc}      = $keys->{hash};
    $conf->{oidcServiceKeyTypeEnc}    = $type;
}

( $lmconf->saveConf($conf) > 0 ) or die $Lemonldap::NG::Common::Conf::msg;

print "Configuration saved\n" if $debug;

exit 0;

__END__

=encoding UTF-8

=head1 NAME

rotateOidcKeys - rotate OpenID Connect signing keys

=head1 SYNOPSIS

  rotateOidcKeys [<options>]

B<Options>:

=over

=item B<--help>: Show this help message

=item B<--debug>: Increase verbosity of output

=back

=head1 DESCRIPTION

rotateOidcKeys is a script that you can run in your crontab to periodically
renew you OpenID Connect signing keys.


=head1 SEE ALSO

L<http://lemonldap-ng.org/>

=head1 AUTHORS

=over

=item Clement Oudot, E<lt>clement@oodo.netE<gt>

=item Xavier Guimard, E<lt>yadd@debian.orgE<gt>

=item Maxime Besson, E<lt>maxime.besson@worteks.comE<gt>

=item Christophe Maudoux, E<lt>chrmdx@gmail.comE<gt>

=back

=head1 BUG REPORT

Use OW2 system to report bug or ask for features:
L<https://gitlab.ow2.org/lemonldap-ng/lemonldap-ng/issues>


=head1 COPYRIGHT AND LICENSE

=over

=item Copyright (C) 2016 by Xavier Guimard, E<lt>x.guimard@free.frE<gt>

=item Copyright (C) 2016 by Clément Oudot, E<lt>clem.oudot@gmail.comE<gt>

=back

This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see L<http://www.gnu.org/licenses/>.

=cut
