Bug 35536: Add Koha::Plugins->RemovePlugins class method
[koha.git] / Koha / Token.pm
1 package Koha::Token;
2
3 # Created as wrapper for CSRF and JWT tokens, but designed for more general use
4
5 # Copyright 2016 Rijksmuseum
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 =head1 NAME
23
24 Koha::Token - Tokenizer
25
26 =head1 SYNOPSIS
27
28     use Koha::Token;
29     my $tokenizer = Koha::Token->new;
30     my $token = $tokenizer->generate({ length => 20 });
31
32     # safely generate a CSRF token (nonblocking)
33     my $csrf_token = $tokenizer->generate({
34         type => 'CSRF', id => $id, secret => $secret,
35     });
36
37     # generate/check CSRF token with defaults and session id
38     my $csrf_token = $tokenizer->generate_csrf({ session_id => $x });
39     my $result = $tokenizer->check_csrf({
40         session_id => $x, token => $token,
41     });
42
43 =head1 DESCRIPTION
44
45     Designed for providing general tokens.
46     Created due to the need for a nonblocking call to Bytes::Random::Secure
47     when generating a CSRF token.
48
49 =cut
50
51 use Modern::Perl;
52 use Bytes::Random::Secure;
53 use String::Random;
54 use WWW::CSRF;
55 use Mojo::JWT;
56 use Digest::MD5 qw( md5_base64 );
57 use Encode;
58 use C4::Context;
59 use Koha::Exceptions::Token;
60 use Koha::Session;
61
62 use base qw(Class::Accessor);
63 use constant HMAC_SHA1_LENGTH => 20;
64 use constant CSRF_EXPIRY_HOURS => 8; # 8 hours instead of 7 days..
65 use constant DEFA_SESSION_ID => 0;
66 use constant DEFA_SESSION_USERID => 'anonymous';
67
68 =head1 METHODS
69
70 =head2 new
71
72     Create object (via Class::Accessor).
73
74 =cut
75
76 sub new {
77     my ( $class ) = @_;
78     return $class->SUPER::new();
79 }
80
81 =head2 generate
82
83     my $token = $tokenizer->generate({ length => 20 });
84     my $csrf_token = $tokenizer->generate({
85         type => 'CSRF', id => $id, secret => $secret,
86     });
87     my $jwt = $tokenizer->generate({
88         type => 'JWT, id => $id, secret => $secret,
89     });
90
91     Generate several types of tokens. Now includes CSRF.
92     For non-CSRF tokens an optional pattern parameter overrides length.
93     Room for future extension.
94
95     Pattern parameter could be write down using this subset of regular expressions:
96     \w    Alphanumeric + "_".
97     \d    Digits.
98     \W    Printable characters other than those in \w.
99     \D    Printable characters other than those in \d.
100     .     Printable characters.
101     []    Character classes.
102     {}    Repetition.
103     *     Same as {0,}.
104     ?     Same as {0,1}.
105     +     Same as {1,}.
106
107 =cut
108
109 sub generate {
110     my ( $self, $params ) = @_;
111     if( $params->{type} && $params->{type} eq 'CSRF' ) {
112         $self->{lasttoken} = _gen_csrf( $params );
113     } elsif( $params->{type} && $params->{type} eq 'JWT' ) {
114         $self->{lasttoken} = _gen_jwt( $params );
115     } else {
116         $self->{lasttoken} = _gen_rand( $params );
117     }
118     return $self->{lasttoken};
119 }
120
121 =head2 generate_csrf
122
123     Like: generate({ type => 'CSRF', ... })
124     Note: id defaults to userid from context, secret to database password.
125     session_id is mandatory; it is combined with id.
126
127 =cut
128
129 sub generate_csrf {
130     my ( $self, $params ) = @_;
131     return if !$params->{session_id};
132     $params = _add_default_csrf_params( $params );
133     return $self->generate({ %$params, type => 'CSRF' });
134 }
135
136 =head2 generate_jwt
137
138     Like: generate({ type => 'JWT', ... })
139     Note that JWT is designed to encode a structure but here we are actually only allowing a value
140     that will be store in the key 'id'.
141
142 =cut
143
144 sub generate_jwt {
145     my ( $self, $params ) = @_;
146     return if !$params->{id};
147     $params = _add_default_jwt_params( $params );
148     return $self->generate({ %$params, type => 'JWT' });
149 }
150
151 =head2 check
152
153     my $result = $tokenizer->check({
154         type => 'CSRF', id => $id, token => $token,
155     });
156
157     Check several types of tokens. Now includes CSRF.
158     Room for future extension.
159
160 =cut
161
162 sub check {
163     my ( $self, $params ) = @_;
164     if( $params->{type} && $params->{type} eq 'CSRF' ) {
165         return _chk_csrf( $params );
166     }
167     elsif( $params->{type} && $params->{type} eq 'JWT' ) {
168         return _chk_jwt( $params );
169     }
170     return;
171 }
172
173 =head2 check_csrf
174
175     Like: check({ type => 'CSRF', ... })
176     Note: id defaults to userid from context, secret to database password.
177     session_id is mandatory; it is combined with id.
178
179 =cut
180
181 sub check_csrf {
182     my ( $self, $params ) = @_;
183     return if !$params->{session_id};
184     $params = _add_default_csrf_params( $params );
185     my $c = $self->check({ %$params, type => 'CSRF' });
186
187     unless ( $c ) {
188         # If the check failed we need to test with the "anonymous" in case the token was generating without the user being logged in yet.
189         $params->{id} = DEFA_SESSION_USERID . '_' . $params->{session_id};
190         $c = $self->check({ %$params, type => 'CSRF' });
191     }
192
193     return $c;
194 }
195
196 =head2 check_jwt
197
198     Like: check({ type => 'JWT', id => $id, token => $token })
199
200     Will return true if the token contains the passed id
201
202 =cut
203
204 sub check_jwt {
205     my ( $self, $params ) = @_;
206     $params = _add_default_jwt_params( $params );
207     return $self->check({ %$params, type => 'JWT' });
208 }
209
210 =head2 decode_jwt
211
212     $tokenizer->decode_jwt({ type => 'JWT', token => $token })
213
214     Will return the value of the id stored in the token.
215
216 =cut
217 sub decode_jwt {
218     my ( $self, $params ) = @_;
219     $params = _add_default_jwt_params( $params );
220     return _decode_jwt( $params );
221 }
222
223 # --- Internal routines ---
224
225 sub _add_default_csrf_params {
226     my ( $params ) = @_;
227     $params->{session_id} //= DEFA_SESSION_ID;
228
229     my $id;
230     my $session = Koha::Session->get_session( { sessionID => $params->{session_id} } );
231     if ($session) {
232         $id = $session->param('id');
233     }
234     if ( !$id ) {
235         $id = DEFA_SESSION_USERID;
236     }
237
238     $params->{id} //= Encode::encode( 'UTF-8', $id );
239     $params->{id} .= '_' . $params->{session_id};
240
241     my $pw = C4::Context->config('pass');
242     $params->{secret} //= md5_base64( Encode::encode( 'UTF-8', $pw ) ),
243     return $params;
244 }
245
246 sub _gen_csrf {
247
248 # Since WWW::CSRF::generate_csrf_token does not use the NonBlocking
249 # parameter of Bytes::Random::Secure, we are passing random bytes from
250 # a non blocking source to WWW::CSRF via its Random parameter.
251
252     my ( $params ) = @_;
253     return if !$params->{id} || !$params->{secret};
254
255
256     my $randomizer = Bytes::Random::Secure->new( NonBlocking => 1 );
257         # this is most fundamental: do not use /dev/random since it is
258         # blocking, but use /dev/urandom !
259     my $random = $randomizer->bytes( HMAC_SHA1_LENGTH );
260     my $token = WWW::CSRF::generate_csrf_token(
261         $params->{id}, $params->{secret}, { Random => $random },
262     );
263
264     return $token;
265 }
266
267 sub _chk_csrf {
268     my ( $params ) = @_;
269     return if !$params->{id} || !$params->{secret} || !$params->{token};
270
271     my $csrf_status = WWW::CSRF::check_csrf_token(
272         $params->{id},
273         $params->{secret},
274         $params->{token},
275         { MaxAge => $params->{MaxAge} // ( CSRF_EXPIRY_HOURS * 3600 ) },
276     );
277     return $csrf_status == WWW::CSRF::CSRF_OK();
278 }
279
280 sub _gen_rand {
281     my ( $params ) = @_;
282     my $length = $params->{length} || 1;
283     $length = 1 unless $length > 0;
284     my $pattern = $params->{pattern} // '.{'.$length.'}'; # pattern overrides length parameter
285
286     my $token;
287     eval {
288         $token = String::Random::random_regex( $pattern );
289     };
290     Koha::Exceptions::Token::BadPattern->throw($@) if $@;
291     return $token;
292 }
293
294 sub _add_default_jwt_params {
295     my ( $params ) = @_;
296     my $pw = C4::Context->config('pass');
297     $params->{secret} //= md5_base64( Encode::encode( 'UTF-8', $pw ) ),
298     return $params;
299 }
300
301 sub _gen_jwt {
302     my ( $params ) = @_;
303     return if !$params->{id} || !$params->{secret};
304
305     return Mojo::JWT->new(
306         claims => { id => $params->{id} },
307         secret => $params->{secret}
308     )->encode;
309 }
310
311 sub _chk_jwt {
312     my ( $params ) = @_;
313     return if !$params->{id} || !$params->{secret} || !$params->{token};
314
315     my $claims = Mojo::JWT->new(secret => $params->{secret})->decode($params->{token});
316
317     return 1 if exists $claims->{id} && $claims->{id} eq $params->{id};
318 }
319
320 sub _decode_jwt {
321     my ( $params ) = @_;
322     return if !$params->{token} || !$params->{secret};
323
324     my $claims = Mojo::JWT->new(secret => $params->{secret})->decode($params->{token});
325
326     return $claims->{id};
327 }
328
329 =head1 AUTHOR
330
331     Marcel de Rooy, Rijksmuseum Amsterdam, The Netherlands
332
333 =cut
334
335 1;