Line 0
Link Here
|
|
|
1 |
package Koha::Middleware::CSRF; |
2 |
|
3 |
# This file is part of Koha. |
4 |
# |
5 |
# Koha is free software; you can redistribute it and/or modify it |
6 |
# under the terms of the GNU General Public License as published by |
7 |
# the Free Software Foundation; either version 3 of the License, or |
8 |
# (at your option) any later version. |
9 |
# |
10 |
# Koha is distributed in the hope that it will be useful, but |
11 |
# WITHOUT ANY WARRANTY; without even the implied warranty of |
12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
13 |
# GNU General Public License for more details. |
14 |
# |
15 |
# You should have received a copy of the GNU General Public License |
16 |
# along with Koha; if not, see <http://www.gnu.org/licenses>. |
17 |
|
18 |
use Modern::Perl; |
19 |
|
20 |
use parent qw(Plack::Middleware); |
21 |
|
22 |
use Koha::Logger; |
23 |
|
24 |
sub call { |
25 |
my ( $self, $env ) = @_; |
26 |
my $req = Plack::Request->new($env); |
27 |
|
28 |
my %stateless_methods = ( |
29 |
GET => 1, |
30 |
HEAD => 1, |
31 |
OPTIONS => 1, |
32 |
TRACE => 1, |
33 |
); |
34 |
|
35 |
my %stateful_methods = ( |
36 |
POST => 1, |
37 |
PUT => 1, |
38 |
DELETE => 1, |
39 |
PATCH => 1, |
40 |
); |
41 |
|
42 |
my $original_op = $req->param('op'); |
43 |
my $request_method = $req->method // q{}; |
44 |
my ( $error ); |
45 |
if ( $stateless_methods{$request_method} && defined $original_op && $original_op =~ m{^cud-} ) { |
46 |
$error = sprintf "Programming error - op '%s' must not start with 'cud-' for %s", $original_op, |
47 |
$request_method; |
48 |
} elsif ( $stateful_methods{$request_method} ) { |
49 |
|
50 |
# Get the CSRF token from the param list or the header |
51 |
my $csrf_token = $req->param('csrf_token') || $req->header('HTTP_CSRF_TOKEN'); |
52 |
|
53 |
if ( defined $req->param('op') && $original_op !~ m{^cud-} ) { |
54 |
$error = sprintf "Programming error - op '%s' must start with 'cud-' for %s", $original_op, |
55 |
$request_method; |
56 |
} elsif ( !$csrf_token ) { |
57 |
$error = sprintf "Programming error - No CSRF token passed for %s", $request_method; |
58 |
} else { |
59 |
unless ( |
60 |
Koha::Token->new->check_csrf( |
61 |
{ |
62 |
session_id => scalar $req->cookies->{CGISESSID}, |
63 |
token => $csrf_token, |
64 |
} |
65 |
) |
66 |
) |
67 |
{ |
68 |
$error = "wrong_csrf_token"; |
69 |
} |
70 |
} |
71 |
} |
72 |
|
73 |
if ( $error ) { |
74 |
Koha::Logger->get->warn( $error ); |
75 |
$env->{KOHA_ERROR} = $error; |
76 |
$env->{PATH_INFO} = '/intranet/errors/403.pl'; |
77 |
} |
78 |
|
79 |
return $self->app->($env); |
80 |
} |
81 |
|
82 |
1; |