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