2ndFA.pm 8.19 KB
Newer Older
1
package Lemonldap::NG::Manager::2ndFA;
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

use 5.10.0;
use utf8;
use strict;
use Mouse;
use MIME::Base64 qw(encode_base64 decode_base64);

use Lemonldap::NG::Common::Session;
use Lemonldap::NG::Common::Conf::Constants;
use Lemonldap::NG::Common::PSGI::Constants;
use Lemonldap::NG::Common::Conf::ReConstants;

use feature 'state';

extends 'Lemonldap::NG::Common::Conf::AccessLib',
  'Lemonldap::NG::Common::Session::REST';

19
our $VERSION = '2.0.2';
20 21 22 23 24

#############################
# I. INITIALIZATION METHODS #
#############################

25
use constant defaultRoute => '2ndfa.html';
26 27 28 29

sub addRoutes {
    my ( $self, $conf ) = @_;

30
    # Remote Procedure are defined in Lemonldap::NG::Common::Session::REST
31
    # HTML template
32
    $self->addRoute( '2ndfa.html', undef, ['GET'] )
33 34 35 36 37 38

      ->addRoute(
        sfa => { ':sessionType' => 'sfa' },
        ['GET']
      )

39
      # DELETE 2FA DEVICE
40
      ->addRoute(
Christophe Maudoux's avatar
Christophe Maudoux committed
41
        sfa => { ':sessionType' => { ':sessionId' => 'del2F' } },
42
        ['DELETE']
43
      );
44 45 46 47

    $self->setTypes($conf);
    $self->{multiValuesSeparator} ||= '; ';
    $self->{hiddenAttributes} //= "_password";
48
    $self->{TOTPCheck} = $self->{U2FCheck} = $self->{UBKCheck}  = '1';
49 50
}

51 52 53
###################
# II. 2FA METHODS #
###################
54

Christophe Maudoux's avatar
Christophe Maudoux committed
55
sub del2F {
56

Christophe Maudoux's avatar
Christophe Maudoux committed
57 58 59
    my ( $self, $req, $session, $skey ) = @_;

    my $mod = $self->getMod($req)
Christophe Maudoux's avatar
Christophe Maudoux committed
60
      or return $self->sendError( $req, 'Bad mode', 400 );
Christophe Maudoux's avatar
Christophe Maudoux committed
61

Christophe Maudoux's avatar
Christophe Maudoux committed
62
    my $params = $req->parameters();
Xavier Guimard's avatar
Xavier Guimard committed
63 64 65 66
    my $type   = $params->{type}
      or return $self->sendError( $req, 'Missing "type" parameter', 400 );
    my $epoch = $params->{epoch}
      or return $self->sendError( $req, 'Missing "epoch" parameter', 400 );
Christophe Maudoux's avatar
Christophe Maudoux committed
67 68

    if ( $type =~ /\b(?:U2F|TOTP|UBK)\b/ ) {
Christophe Maudoux's avatar
Christophe Maudoux committed
69 70
        $self->logger->debug(
            "Call procedure delete2F with type=$type and epoch=$epoch");
71
        return $self->delete2F( $req, $session, $skey );
Christophe Maudoux's avatar
Christophe Maudoux committed
72 73
    }
    else {
Christophe Maudoux's avatar
Christophe Maudoux committed
74
        return $self->sendError( $req, 'Bad value "type" parameter', 400 );
Christophe Maudoux's avatar
Christophe Maudoux committed
75
    }
76 77
}

78 79 80 81 82 83 84 85
########################
# III. DISPLAY METHODS #
########################

sub sfa {
    my ( $self, $req, $session, $skey ) = @_;

    # Case 1: only one session is required
Christophe Maudoux's avatar
Christophe Maudoux committed
86
    if ($session) {
87 88
        return $self->session( $req, $session, $skey );
    }
Christophe Maudoux's avatar
Christophe Maudoux committed
89

90
    my $mod = $self->getMod($req)
Christophe Maudoux's avatar
Christophe Maudoux committed
91
      or return $self->sendError( $req, 'Bad mode', 400 );
92 93 94 95
    my $params = $req->parameters();
    my $type   = delete $params->{sessionType};
    $type = ucfirst($type);
    my $res;
Xavier Guimard's avatar
Xavier Guimard committed
96

97 98 99 100 101
    # Case 2: list of sessions

    my $whatToTrace = Lemonldap::NG::Handler::PSGI::Main->tsv->{whatToTrace};

    # 2.1 Get fields to require
Christophe Maudoux's avatar
Christophe Maudoux committed
102
    my @fields = ( '_httpSessionType', $whatToTrace, '_2fDevices' );
103 104 105 106 107 108 109 110 111 112 113 114 115
    if ( my $groupBy = $params->{groupBy} ) {
        $groupBy =~ s/^substr\((\w+)(?:,\d+(?:,\d+)?)?\)$/$1/;
        $groupBy =~ s/^_whatToTrace$/$whatToTrace/o
          or push @fields, $groupBy;
    }
    else {
        push @fields, '_utime';
    }

    # 2.2 Restrict query if possible: search for filters (any query arg that is
    #     not a keyword)
    my $moduleOptions = $mod->{options};
    $moduleOptions->{backend} = $mod->{module};
Christophe Maudoux's avatar
Christophe Maudoux committed
116

Christophe Maudoux's avatar
Christophe Maudoux committed
117
    # Select 2FA sessions to display
Christophe Maudoux's avatar
Christophe Maudoux committed
118
    foreach (qw(U2F TOTP UBK)) {
119 120
        $self->{ $_ . 'Check' } = delete $params->{ $_ . 'Check' }
          if ( defined $params->{ $_ . 'Check' } );
Christophe Maudoux's avatar
Christophe Maudoux committed
121 122
    }

123 124 125
    my %filters = map {
        my $s = $_;
        $s =~ s/\b_whatToTrace\b/$whatToTrace/o;
Christophe Maudoux's avatar
Christophe Maudoux committed
126
        /^groupBy$/
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
          ? ()
          : ( $s => $params->{$_} );
    } keys %$params;
    $filters{_session_kind} = $type;

    push @fields, keys(%filters);
    {
        my %seen;
        @fields = grep { !$seen{$_}++ } @fields;
    }

    # For now, only one argument can be passed to
    # Lemonldap::NG::Common::Apache::Session so just the first filter is
    # used
    my ($firstFilter) = sort {
            $filters{$a} =~ m#^[\w:]+/\d+\*?$# ? 1
          : $filters{$b} =~ m#^[\w:]+/\d+\*?$# ? -1
          : $a eq '_session_kind'              ? 1
          : $b eq '_session_kind'              ? -1
          : $a cmp $b
    } keys %filters;

    # Check if a '*' is required
    my $function = 'searchOn';
    $function = 'searchOnExpr'
      if ( grep { /\*/ and not m#^[\w:]+/\d+\*?$# }
        ( $filters{$firstFilter} ) );
    $self->logger->debug(
        "First filter: $firstFilter = $filters{$firstFilter} ($function)");

    $res =
      Lemonldap::NG::Common::Apache::Session->$function( $moduleOptions,
        $firstFilter, $filters{$firstFilter}, @fields );

    return $self->sendJSONresponse(
        $req,
        {
            result => 1,
            count  => 0,
            total  => 0,
            values => []
        }
    ) unless ( $res and %$res );

    delete $filters{$firstFilter}
      unless ( grep { /\*/ and not m#^[\w:]+/\d+\*?$# }
        ( $filters{$firstFilter} ) );
    foreach my $k ( keys %filters ) {
        $self->logger->debug("Removing unless $k =~ /^$filters{$k}\$/");
176 177 178 179
        $filters{$k} =~ s/\./\\./g;
        $filters{$k} =~ s/\*/\.\*/g;
        foreach my $session ( keys %$res ) {
            if ( $res->{$session}->{$k} ) {
180
                delete $res->{$session}
181
                  unless ( $res->{$session}->{$k} =~ /^$filters{$k}$/ );
182 183 184 185
            }
        }
    }

186 187 188 189 190 191 192 193 194
    # Remove sessions without at least one 2F device(s)
    $self->logger->debug(
        "Removing sessions without at least one 2F device(s)...");
    foreach my $session ( keys %$res ) {
        delete $res->{$session}
          unless ( defined $res->{$session}->{_2fDevices}
            and $res->{$session}->{_2fDevices} =~
            /"type":\s*"(?:U2F|TOTP|UBK)"/s );
    }
195

Christophe Maudoux's avatar
Christophe Maudoux committed
196
    # Filter 2FA sessions if needed
Christophe Maudoux's avatar
Christophe Maudoux committed
197 198
    $self->logger->debug("Filtering 2F sessions...");
    my $all = ( keys %$res );
Christophe Maudoux's avatar
Christophe Maudoux committed
199
    foreach (qw(U2F TOTP UBK)) {
200 201 202 203 204 205 206 207
        if ( $self->{ $_ . 'Check' } eq '2' ) {
            foreach my $session ( keys %$res ) {
                delete $res->{$session}
                  unless ( defined $res->{$session}->{_2fDevices}
                    and $res->{$session}->{_2fDevices} =~ /"type":\s*"$_"/s );
            }
            $self->logger->debug(
                "Removing sessions unless a $_ device is registered");
Christophe Maudoux's avatar
Christophe Maudoux committed
208 209 210
        }
    }

211
    my $total = ( keys %$res );
212
    $self->logger->debug("2FA session(s) left : $total / $all");
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

    if ( my $group = $req->params('groupBy') ) {
        my $r;
        $group =~ s/\b_whatToTrace\b/$whatToTrace/o;

        # Substrings
        if ( $group =~ /^substr\((\w+)(?:,(\d+)(?:,(\d+))?)?\)$/ ) {
            my ( $field, $length, $start ) = ( $1, $2, $3 );
            $start ||= 0;
            $length = 1 if ( $length < 1 );
            foreach my $k ( keys %$res ) {
                $r->{ substr $res->{$k}->{$field}, $start, $length }++
                  if ( $res->{$k}->{$field} );
            }
            $group = $field;
        }

        # Simple field groupBy query
        elsif ( $group =~ /^\w+$/ ) {
            eval {
                foreach my $k ( keys %$res ) {
                    $r->{ $res->{$k}->{$group} }++;
                }
            };
            return $self->sendError(
                $req,
qq{Use of an uninitialized attribute "$group" to group sessions},
                400
            ) if ($@);
        }
        else {
            return $self->sendError( $req, 'Syntax error in groupBy', 400 );
        }

        # Build result
        $res = [
            sort {
                my @a = ( $a->{value} =~ /^(\d+)(?:\.(\d+))*$/ );
                my @b = ( $b->{value} =~ /^(\d+)(?:\.(\d+))*$/ );
                ( @a and @b )
                  ? ( $a[0] <=> $b[0]
                      or $a[1] <=> $b[1]
                      or $a[2] <=> $b[2]
                      or $a[3] <=> $b[3] )
                  : $a->{value} cmp $b->{value}
              }
              map { { value => $_, count => $r->{$_} } } keys %$r
        ];
    }

    # Else, $res elements will be like:
Christophe Maudoux's avatar
Christophe Maudoux committed
264
    #   { session => <sessionId>, userId => <_session_uid> }
265 266 267
    else {
        $res = [
            sort { $a->{date} <=> $b->{date} }
268
              map { { session => $_, userId => $res->{$_}->{_session_uid} } }
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
              keys %$res
        ];
    }

    return $self->sendJSONresponse(
        $req,
        {
            result => 1,
            count  => scalar(@$res),
            total  => $total,
            values => $res
        }
    );
}

1;