Bug 29812: Add missing use C4::Context in Koha::Token
[koha.git] / Koha / Token.pm
1 package Koha::Token;
2
3 # Created as wrapper for CSRF 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 Digest::MD5 qw( md5_base64 );
56 use Encode;
57 use C4::Context;
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
83     Generate several types of tokens. Now includes CSRF.
84     For non-CSRF tokens an optional pattern parameter overrides length.
85     Room for future extension.
86
87     Pattern parameter could be write down using this subset of regular expressions:
88     \w    Alphanumeric + "_".
89     \d    Digits.
90     \W    Printable characters other than those in \w.
91     \D    Printable characters other than those in \d.
92     .     Printable characters.
93     []    Character classes.
94     {}    Repetition.
95     *     Same as {0,}.
96     ?     Same as {0,1}.
97     +     Same as {1,}.
98
99 =cut
100
101 sub generate {
102     my ( $self, $params ) = @_;
103     if( $params->{type} && $params->{type} eq 'CSRF' ) {
104         $self->{lasttoken} = _gen_csrf( $params );
105     } else {
106         $self->{lasttoken} = _gen_rand( $params );
107     }
108     return $self->{lasttoken};
109 }
110
111 =head2 generate_csrf
112
113     Like: generate({ type => 'CSRF', ... })
114     Note: id defaults to userid from context, secret to database password.
115     session_id is mandatory; it is combined with id.
116
117 =cut
118
119 sub generate_csrf {
120     my ( $self, $params ) = @_;
121     return if !$params->{session_id};
122     $params = _add_default_csrf_params( $params );
123     return $self->generate({ %$params, type => 'CSRF' });
124 }
125
126 =head2 check
127
128     my $result = $tokenizer->check({
129         type => 'CSRF', id => $id, token => $token,
130     });
131
132     Check several types of tokens. Now includes CSRF.
133     Room for future extension.
134
135 =cut
136
137 sub check {
138     my ( $self, $params ) = @_;
139     if( $params->{type} && $params->{type} eq 'CSRF' ) {
140         return _chk_csrf( $params );
141     }
142     return;
143 }
144
145 =head2 check_csrf
146
147     Like: check({ type => 'CSRF', ... })
148     Note: id defaults to userid from context, secret to database password.
149     session_id is mandatory; it is combined with id.
150
151 =cut
152
153 sub check_csrf {
154     my ( $self, $params ) = @_;
155     return if !$params->{session_id};
156     $params = _add_default_csrf_params( $params );
157     return $self->check({ %$params, type => 'CSRF' });
158 }
159
160 # --- Internal routines ---
161
162 sub _add_default_csrf_params {
163     my ( $params ) = @_;
164     $params->{session_id} //= '';
165     if( !$params->{id} ) {
166         $params->{id} = Encode::encode( 'UTF-8', C4::Context->userenv->{id} . $params->{session_id} );
167     } else {
168         $params->{id} .= $params->{session_id};
169     }
170     $params->{id} //= Encode::encode( 'UTF-8', C4::Context->userenv->{id} );
171     my $pw = C4::Context->config('pass');
172     $params->{secret} //= md5_base64( Encode::encode( 'UTF-8', $pw ) ),
173     return $params;
174 }
175
176 sub _gen_csrf {
177
178 # Since WWW::CSRF::generate_csrf_token does not use the NonBlocking
179 # parameter of Bytes::Random::Secure, we are passing random bytes from
180 # a non blocking source to WWW::CSRF via its Random parameter.
181
182     my ( $params ) = @_;
183     return if !$params->{id} || !$params->{secret};
184
185
186     my $randomizer = Bytes::Random::Secure->new( NonBlocking => 1 );
187         # this is most fundamental: do not use /dev/random since it is
188         # blocking, but use /dev/urandom !
189     my $random = $randomizer->bytes( HMAC_SHA1_LENGTH );
190     my $token = WWW::CSRF::generate_csrf_token(
191         $params->{id}, $params->{secret}, { Random => $random },
192     );
193
194     return $token;
195 }
196
197 sub _chk_csrf {
198     my ( $params ) = @_;
199     return if !$params->{id} || !$params->{secret} || !$params->{token};
200
201     my $csrf_status = WWW::CSRF::check_csrf_token(
202         $params->{id},
203         $params->{secret},
204         $params->{token},
205         { MaxAge => $params->{MaxAge} // ( CSRF_EXPIRY_HOURS * 3600 ) },
206     );
207     return $csrf_status == WWW::CSRF::CSRF_OK();
208 }
209
210 sub _gen_rand {
211     my ( $params ) = @_;
212     my $length = $params->{length} || 1;
213     $length = 1 unless $length > 0;
214     my $pattern = $params->{pattern} // '.{'.$length.'}'; # pattern overrides length parameter
215
216     my $token;
217     eval {
218         $token = String::Random::random_regex( $pattern );
219     };
220     Koha::Exceptions::Token::BadPattern->throw($@) if $@;
221     return $token;
222 }
223
224 =head1 AUTHOR
225
226     Marcel de Rooy, Rijksmuseum Amsterdam, The Netherlands
227
228 =cut
229
230 1;