Bug 21998: Add pattern parameter 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 under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 3 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 qw( encode );
57 use base qw(Class::Accessor);
58 use constant HMAC_SHA1_LENGTH => 20;
59 use constant CSRF_EXPIRY_HOURS => 8; # 8 hours instead of 7 days..
60
61 =head1 METHODS
62
63 =head2 new
64
65     Create object (via Class::Accessor).
66
67 =cut
68
69 sub new {
70     my ( $class ) = @_;
71     return $class->SUPER::new();
72 }
73
74 =head2 generate
75
76     my $token = $tokenizer->generate({ length => 20 });
77     my $csrf_token = $tokenizer->generate({
78         type => 'CSRF', id => $id, secret => $secret,
79     });
80
81     Generate several types of tokens. Now includes CSRF.
82     For non-CSRF tokens an optional pattern parameter overrides length.
83     Room for future extension.
84
85 =cut
86
87 sub generate {
88     my ( $self, $params ) = @_;
89     if( $params->{type} && $params->{type} eq 'CSRF' ) {
90         $self->{lasttoken} = _gen_csrf( $params );
91     } else {
92         $self->{lasttoken} = _gen_rand( $params );
93     }
94     return $self->{lasttoken};
95 }
96
97 =head2 generate_csrf
98
99     Like: generate({ type => 'CSRF', ... })
100     Note: id defaults to userid from context, secret to database password.
101     session_id is mandatory; it is combined with id.
102
103 =cut
104
105 sub generate_csrf {
106     my ( $self, $params ) = @_;
107     return if !$params->{session_id};
108     $params = _add_default_csrf_params( $params );
109     return $self->generate({ %$params, type => 'CSRF' });
110 }
111
112 =head2 check
113
114     my $result = $tokenizer->check({
115         type => 'CSRF', id => $id, token => $token,
116     });
117
118     Check several types of tokens. Now includes CSRF.
119     Room for future extension.
120
121 =cut
122
123 sub check {
124     my ( $self, $params ) = @_;
125     if( $params->{type} && $params->{type} eq 'CSRF' ) {
126         return _chk_csrf( $params );
127     }
128     return;
129 }
130
131 =head2 check_csrf
132
133     Like: check({ type => 'CSRF', ... })
134     Note: id defaults to userid from context, secret to database password.
135     session_id is mandatory; it is combined with id.
136
137 =cut
138
139 sub check_csrf {
140     my ( $self, $params ) = @_;
141     return if !$params->{session_id};
142     $params = _add_default_csrf_params( $params );
143     return $self->check({ %$params, type => 'CSRF' });
144 }
145
146 # --- Internal routines ---
147
148 sub _add_default_csrf_params {
149     my ( $params ) = @_;
150     $params->{session_id} //= '';
151     if( !$params->{id} ) {
152         $params->{id} = Encode::encode( 'UTF-8', C4::Context->userenv->{id} . $params->{session_id} );
153     } else {
154         $params->{id} .= $params->{session_id};
155     }
156     $params->{id} //= Encode::encode( 'UTF-8', C4::Context->userenv->{id} );
157     my $pw = C4::Context->config('pass');
158     $params->{secret} //= md5_base64( Encode::encode( 'UTF-8', $pw ) ),
159     return $params;
160 }
161
162 sub _gen_csrf {
163
164 # Since WWW::CSRF::generate_csrf_token does not use the NonBlocking
165 # parameter of Bytes::Random::Secure, we are passing random bytes from
166 # a non blocking source to WWW::CSRF via its Random parameter.
167
168     my ( $params ) = @_;
169     return if !$params->{id} || !$params->{secret};
170
171
172     my $randomizer = Bytes::Random::Secure->new( NonBlocking => 1 );
173         # this is most fundamental: do not use /dev/random since it is
174         # blocking, but use /dev/urandom !
175     my $random = $randomizer->bytes( HMAC_SHA1_LENGTH );
176     my $token = WWW::CSRF::generate_csrf_token(
177         $params->{id}, $params->{secret}, { Random => $random },
178     );
179
180     return $token;
181 }
182
183 sub _chk_csrf {
184     my ( $params ) = @_;
185     return if !$params->{id} || !$params->{secret} || !$params->{token};
186
187     my $csrf_status = WWW::CSRF::check_csrf_token(
188         $params->{id},
189         $params->{secret},
190         $params->{token},
191         { MaxAge => $params->{MaxAge} // ( CSRF_EXPIRY_HOURS * 3600 ) },
192     );
193     return $csrf_status == WWW::CSRF::CSRF_OK();
194 }
195
196 sub _gen_rand {
197     my ( $params ) = @_;
198     my $length = $params->{length} || 1;
199     $length = 1 unless $length > 0;
200     my $pattern = $params->{pattern} // '.{'.$length.'}'; # pattern overrides length parameter
201     return String::Random::random_regex( $pattern );
202 }
203
204 =head1 AUTHOR
205
206     Marcel de Rooy, Rijksmuseum Amsterdam, The Netherlands
207
208 =cut
209
210 1;