Bug 27849: Koha::Token may access undefined C4::Context->userenv
[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 base qw(Class::Accessor);
61 use constant HMAC_SHA1_LENGTH => 20;
62 use constant CSRF_EXPIRY_HOURS => 8; # 8 hours instead of 7 days..
63
64 =head1 METHODS
65
66 =head2 new
67
68     Create object (via Class::Accessor).
69
70 =cut
71
72 sub new {
73     my ( $class ) = @_;
74     return $class->SUPER::new();
75 }
76
77 =head2 generate
78
79     my $token = $tokenizer->generate({ length => 20 });
80     my $csrf_token = $tokenizer->generate({
81         type => 'CSRF', id => $id, secret => $secret,
82     });
83     my $jwt = $tokenizer->generate({
84         type => 'JWT, id => $id, secret => $secret,
85     });
86
87     Generate several types of tokens. Now includes CSRF.
88     For non-CSRF tokens an optional pattern parameter overrides length.
89     Room for future extension.
90
91     Pattern parameter could be write down using this subset of regular expressions:
92     \w    Alphanumeric + "_".
93     \d    Digits.
94     \W    Printable characters other than those in \w.
95     \D    Printable characters other than those in \d.
96     .     Printable characters.
97     []    Character classes.
98     {}    Repetition.
99     *     Same as {0,}.
100     ?     Same as {0,1}.
101     +     Same as {1,}.
102
103 =cut
104
105 sub generate {
106     my ( $self, $params ) = @_;
107     if( $params->{type} && $params->{type} eq 'CSRF' ) {
108         $self->{lasttoken} = _gen_csrf( $params );
109     } elsif( $params->{type} && $params->{type} eq 'JWT' ) {
110         $self->{lasttoken} = _gen_jwt( $params );
111     } else {
112         $self->{lasttoken} = _gen_rand( $params );
113     }
114     return $self->{lasttoken};
115 }
116
117 =head2 generate_csrf
118
119     Like: generate({ type => 'CSRF', ... })
120     Note: id defaults to userid from context, secret to database password.
121     session_id is mandatory; it is combined with id.
122
123 =cut
124
125 sub generate_csrf {
126     my ( $self, $params ) = @_;
127     return if !$params->{session_id};
128     $params = _add_default_csrf_params( $params );
129     return $self->generate({ %$params, type => 'CSRF' });
130 }
131
132 =head2 generate_jwt
133
134     Like: generate({ type => 'JWT', ... })
135     Note that JWT is designed to encode a structure but here we are actually only allowing a value
136     that will be store in the key 'id'.
137
138 =cut
139
140 sub generate_jwt {
141     my ( $self, $params ) = @_;
142     return if !$params->{id};
143     $params = _add_default_jwt_params( $params );
144     return $self->generate({ %$params, type => 'JWT' });
145 }
146
147 =head2 check
148
149     my $result = $tokenizer->check({
150         type => 'CSRF', id => $id, token => $token,
151     });
152
153     Check several types of tokens. Now includes CSRF.
154     Room for future extension.
155
156 =cut
157
158 sub check {
159     my ( $self, $params ) = @_;
160     if( $params->{type} && $params->{type} eq 'CSRF' ) {
161         return _chk_csrf( $params );
162     }
163     elsif( $params->{type} && $params->{type} eq 'JWT' ) {
164         return _chk_jwt( $params );
165     }
166     return;
167 }
168
169 =head2 check_csrf
170
171     Like: check({ type => 'CSRF', ... })
172     Note: id defaults to userid from context, secret to database password.
173     session_id is mandatory; it is combined with id.
174
175 =cut
176
177 sub check_csrf {
178     my ( $self, $params ) = @_;
179     return if !$params->{session_id};
180     $params = _add_default_csrf_params( $params );
181     return $self->check({ %$params, type => 'CSRF' });
182 }
183
184 =head2 check_jwt
185
186     Like: check({ type => 'JWT', id => $id, token => $token })
187
188     Will return true if the token contains the passed id
189
190 =cut
191
192 sub check_jwt {
193     my ( $self, $params ) = @_;
194     $params = _add_default_jwt_params( $params );
195     return $self->check({ %$params, type => 'JWT' });
196 }
197
198 =head2 decode_jwt
199
200     $tokenizer->decode_jwt({ type => 'JWT', token => $token })
201
202     Will return the value of the id stored in the token.
203
204 =cut
205 sub decode_jwt {
206     my ( $self, $params ) = @_;
207     $params = _add_default_jwt_params( $params );
208     return _decode_jwt( $params );
209 }
210
211 # --- Internal routines ---
212
213 sub _add_default_csrf_params {
214     my ( $params ) = @_;
215     $params->{session_id} //= '';
216     if( !$params->{id} ) {
217         if( defined( C4::Context->userenv ) ) {
218             $params->{id} = Encode::encode( 'UTF-8', C4::Context->userenv->{id} . $params->{session_id} );
219         } else {
220             $params->{id} = Encode::encode( 'UTF-8', $params->{session_id} );
221         }
222     } else {
223         $params->{id} .= $params->{session_id};
224     }
225     $params->{id} //= Encode::encode( 'UTF-8', C4::Context->userenv->{id} );
226     my $pw = C4::Context->config('pass');
227     $params->{secret} //= md5_base64( Encode::encode( 'UTF-8', $pw ) ),
228     return $params;
229 }
230
231 sub _gen_csrf {
232
233 # Since WWW::CSRF::generate_csrf_token does not use the NonBlocking
234 # parameter of Bytes::Random::Secure, we are passing random bytes from
235 # a non blocking source to WWW::CSRF via its Random parameter.
236
237     my ( $params ) = @_;
238     return if !$params->{id} || !$params->{secret};
239
240
241     my $randomizer = Bytes::Random::Secure->new( NonBlocking => 1 );
242         # this is most fundamental: do not use /dev/random since it is
243         # blocking, but use /dev/urandom !
244     my $random = $randomizer->bytes( HMAC_SHA1_LENGTH );
245     my $token = WWW::CSRF::generate_csrf_token(
246         $params->{id}, $params->{secret}, { Random => $random },
247     );
248
249     return $token;
250 }
251
252 sub _chk_csrf {
253     my ( $params ) = @_;
254     return if !$params->{id} || !$params->{secret} || !$params->{token};
255
256     my $csrf_status = WWW::CSRF::check_csrf_token(
257         $params->{id},
258         $params->{secret},
259         $params->{token},
260         { MaxAge => $params->{MaxAge} // ( CSRF_EXPIRY_HOURS * 3600 ) },
261     );
262     return $csrf_status == WWW::CSRF::CSRF_OK();
263 }
264
265 sub _gen_rand {
266     my ( $params ) = @_;
267     my $length = $params->{length} || 1;
268     $length = 1 unless $length > 0;
269     my $pattern = $params->{pattern} // '.{'.$length.'}'; # pattern overrides length parameter
270
271     my $token;
272     eval {
273         $token = String::Random::random_regex( $pattern );
274     };
275     Koha::Exceptions::Token::BadPattern->throw($@) if $@;
276     return $token;
277 }
278
279 sub _add_default_jwt_params {
280     my ( $params ) = @_;
281     my $pw = C4::Context->config('pass');
282     $params->{secret} //= md5_base64( Encode::encode( 'UTF-8', $pw ) ),
283     return $params;
284 }
285
286 sub _gen_jwt {
287     my ( $params ) = @_;
288     return if !$params->{id} || !$params->{secret};
289
290     return Mojo::JWT->new(
291         claims => { id => $params->{id} },
292         secret => $params->{secret}
293     )->encode;
294 }
295
296 sub _chk_jwt {
297     my ( $params ) = @_;
298     return if !$params->{id} || !$params->{secret} || !$params->{token};
299
300     my $claims = Mojo::JWT->new(secret => $params->{secret})->decode($params->{token});
301
302     return 1 if exists $claims->{id} && $claims->{id} == $params->{id};
303 }
304
305 sub _decode_jwt {
306     my ( $params ) = @_;
307     return if !$params->{token} || !$params->{secret};
308
309     my $claims = Mojo::JWT->new(secret => $params->{secret})->decode($params->{token});
310
311     return $claims->{id};
312 }
313
314 =head1 AUTHOR
315
316     Marcel de Rooy, Rijksmuseum Amsterdam, The Netherlands
317
318 =cut
319
320 1;