Lemonldap-NG-Common
view release on metacpan or search on metacpan
scripts/encryptTotpSecrets view on Meta::CPAN
if ( $conf->{"persistentStorage"} ) {
$args = $conf->{"persistentStorageOptions"};
$args->{backend} = $conf->{"persistentStorage"};
}
else {
$args = $conf->{"globalStorageOptions"};
$args->{backend} = $conf->{"globalStorage"};
}
verbose "Searching for persistent sessions";
$res = Lemonldap::NG::Common::Apache::Session->searchOn( $args, '_session_kind',
'Persistent', '_2fDevices', '_session_uid' );
if ( ref($res) eq "HASH" ) {
verbose "Found " . scalar( keys %{$res} ) . " persistent sessions";
# For each found psession
for my $k ( keys %{$res} ) {
my $_2fDevices = $res->{$k}->{_2fDevices};
my $uid = $res->{$k}->{_session_uid};
verbose "Processing psession $k for user $uid";
encrypt_session( $k, $uid, $_2fDevices );
}
}
else {
die "Could not find any persistent sessions";
}
sub encrypt_session {
my ( $k, $uid, $_2fDevices ) = @_;
eval {
# parse _2fDevices if found
if ($_2fDevices) {
$_2fDevices = from_json($_2fDevices);
# If the session has 2f devices
if ( ref($_2fDevices) eq "ARRAY" and @{$_2fDevices} > 0 ) {
my $changed = convert_keys_for_user( $uid, $_2fDevices );
if ( $changed and !$dryrun ) {
eval { update2fArray( $k, $_2fDevices ); };
if ($@) {
info "Error updating session for $uid: $@";
}
}
}
else {
verbose "User $uid does not have a TOTP";
}
}
else {
verbose "User $uid does not have a TOTP";
}
};
if ($@) {
verbose "Error on psession $k: $@";
}
}
sub update2fArray {
my ( $id, $_2fDevices ) = @_;
my $session = Lemonldap::NG::Common::Session->new(
storageModule => $args->{backend},
storageModuleOptions => $args,
id => $id,
);
unless ( $session->data ) {
die "Error while opening session $id";
}
unless ( $session->update( { _2fDevices => to_json($_2fDevices) } ) ) {
die "Error while updating session $id";
}
}
sub convert_device_for_user {
my ( $uid, $device ) = @_;
my $changed = 0;
# In update mode, decrypt then encrypt
if ($update) {
my $cleartext_secret =
$decrypt_totp->get_cleartext_secret( $device->{_secret} );
if ($cleartext_secret) {
my $newsecret =
$encrypt_totp->get_storable_secret($cleartext_secret);
$device->{_secret} = $newsecret;
$changed = 1;
verbose 'Updated secret for ' . $uid;
}
else {
info 'Unable to decrypt TOTP secret for ' . $uid;
}
# In normal mode, only encrypt non-encrypted secrets
}
else {
if ( !$encrypt_totp->is_encrypted( $device->{_secret} ) ) {
$device->{_secret} =
$encrypt_totp->get_storable_secret( $device->{_secret} );
$changed = 1;
info 'Encrypted TOTP secret for ' . $uid;
}
else {
verbose 'Secret is already encrypted';
}
}
return $changed;
}
sub convert_keys_for_user {
my ( $uid, $devices ) = @_;
my $has_totp = 0;
my $changed = 0;
for my $device ( @{$devices} ) {
if ( $device->{type} eq "TOTP" ) {
$has_totp = 1;
my $epoch = $device->{epoch};
( run in 1.949 second using v1.01-cache-2.11-cpan-39bf76dae61 )