CGI/Application/Plugin/ProtectCSRF.pm

filter: Statementstmt 95.4% 104 / 109 Branchbran 64.5% 31 / 48 Conditioncond 66.6% 10 / 15 MC/DCmcdc 44.4% 4 / 9 Subroutinesub 100% 18 / 18 Podpod 60.0% 3 / 5 totaltotal 83.3% 170 / 204 CC 30 SCAR 18.7
CC
30
Cov
84%
protect_csrf_config
11.4
_csrf_forbidden
9.6
_add_csrf_id
9.4
CRAP 6.5
↑ Summary
1 package CGI::Application::Plugin::ProtectCSRF;
2  
3 =pod
4  
5 =head1 NAME
6  
7 CGI::Application::Plugin::ProtectCSRF - Plug-in protected from CSRF
8  
9 =head1 VERSION
10  
11 1.01
12  
13 =head1 SYNPSIS
14  
15 use Your::App;
16 use base qw(CGI::Application);
17 use CGI::Application::Plugin::Session; # require!!
18 use CGI::Application::Plugin::ProtectCSRF;
19  
20 sub input_form : PublishCSRFID {
21 my $self = shift;
22 do_something();
23 }
24  
25 sub finish : ProtectCSRF {
26 my $self = shift;
27 $self->clear_csrf_id;
28 do_something();
29 }
30  
31 =head1 DESCRIPTION
32  
33 CGI::Application::Plugin::ProtectCSRF is C::A::P protected from CSRF.
34  
35 When CSRF is detected, Forbidden is returned and processing is interrupted.
36  
37 =cut
38  
39 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 5 ▶use base qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
41 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 5 ▶use HTML::TokeParser;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 5 ▶use Digest::SHA1 qw(sha1_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
44 5 ▶use Attribute::Handlers;
Subroutine BEGIN: called CC=1 SCAR=0.0
45  
46 our(
47 5 @EXPORT,
48 $CSRF_ERROR_MODE,
49 $CSRF_ERROR_STATUS,
50 $CSRF_ERROR_TMPL,
51 $CSRF_ID,
52 $CSRF_ID_LENGTH,
53 $CSRF_POST_ONLY,
54 $VERSION
55 );
56  
57 5 @EXPORT = qw(
58 clear_csrf_id
59 csrf_id
60 protect_csrf_config
61 );
62  
63 5 $CSRF_ERROR_MODE = "_csrf_error";
64 5 $CSRF_ERROR_STATUS = 200;
65 5 $CSRF_ERROR_TMPL = \qq{<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
66 <html>
67 <head><title>CSRF ERROR</title></head>
68 <body>
69 <h1>CSRF ERROR</h1>
70 <p>This access is illegal. you don't have permission to access on this server.</p>
71 </body>
72 </html>
73 };
74 5 $CSRF_ID = "_csrf_id";
75 5 $CSRF_POST_ONLY = 0;
76 5 $VERSION = 1.01;
77  
78 5 my(%publish_csrf_id_runmodes, %protect_csrf_runmodes);
79  
80 4 ▶sub import {
Subroutine import: called CC=2 SCAR=7.0
81  
82 4 my $pkg = caller;
83  
84 # C::A::P::Session method check
85 4 ▶ croak("C::A::P::Session module is not load to your app") if !$pkg->can("session");
Branch: 1 branch
BranchTrueFalseTotal
unless $pkg->can("session") 0 4 4
86  
87 4 $pkg->add_callback("prerun", \&_publish_csrf_id);
88 4 $pkg->add_callback("prerun", \&_csrf_forbidden);
89 4 $pkg->add_callback("postrun", \&_add_csrf_id);
90  
91 4 goto &Exporter::import;
92 }
93  
94 =pod
95  
96 =head1 ACTION
97  
98 =head2 PublishCSRFID
99  
100 PublishCSRFID is action publishes CSRF ticket. CSRF ticket is published when I
101 define it as an attribute of runmode method publishing CSRF ticket, and it is saved in session.
102 If there is form tag in HTML to display after the processing end, as for runmode method to
103 publish, CSRF ticket is set automatically by hidden field
104  
105 # publish CSRF ticket
106 sub input_form : PublishCSRFID {
107 my $self = shift;
108 return <<HTML;
109 <form action="foo" method="post">
110 <input type="text" name="name">
111 <input type="submit" value="submit!">
112 <input type="hidden" name="rm" value="finish">
113 </form>
114 HTML
115 }
116
117 # display html source
118 <form action="foo" method="post">
119 <input type="hidden" name="_csrf_id" value="random string" /> <- insert hidden field
120 <input type="text" name="name">
121 <input type="submit" value="submit!">
122 <input type="hidden" name="rm" value="finish">
123 </form>
124  
125 =head2 ProtectCSRF
126  
127 ProtectCSRF is action to protect from CSRF Attack. If session CSRF ticket does not accord
128 with query CSRF ticket, application consideres it to be CSRF attack and refuse to access it.
129 Carry out the processing that you want to perform after having carried out clear_csrf_id method
130 when access it, and it was admitted.
131  
132 sub finish : ProtectCSRF {
133 my $self = shift;
134 $self->clear_csrf_id; # require! There is not a meaning unless I do it
135 do_something(); # The processing that you want to perform (DB processing etc)
136 }
137  
138 =cut
139  
140 4 ▶sub CGI::Application::PublishCSRFID : ATTR(BEGIN) {
Subroutine PublishCSRFID: called CC=1 SCAR=0.0
Pod undocumented
141 4 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
142 4 $publish_csrf_id_runmodes{$referent} = 1;
143 #$publish_csrf_id_runmodes{*{$symbol}{NAME}} = 1;
144 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
145  
146 4 ▶sub CGI::Application::ProtectCSRF : ATTR(BEGIN) {
Subroutine ProtectCSRF: called CC=1 SCAR=0.0
Pod undocumented
147 4 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
148 4 $protect_csrf_runmodes{$referent} = 1;
149 5 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
150  
151 =pod
152  
153 =head1 METHOD
154  
155 =head2 csrf_id
156  
157 Get ticket for protect CSRF
158  
159 Example:
160  
161 sub input_form : PublishCSRFID {
162 my $self = shift;
163  
164 my $csrf_id = $self->csrf_id;
165 do_something();
166 }
167  
168 =cut
169  
170 5 ▶sub csrf_id {
Subroutine csrf_id: called CC=1 SCAR=0.0
Pod documented
171  
172 5 my $self = shift;
173 5 return $self->session->param($self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_id});
174 }
175  
176 =head2 protect_csrf_config
177  
178 Initialize ProtectCSRF
179  
180 Option:
181  
182 csrf_error_status : CSRF error status code (default: 200)
183 csrf_error_mode : CSRF error runmode name (default: _csrf_error)
184 csrf_error_tmpl : CSRF error display html. scalarref or filepath or filehandle (default: $CSRF_ERROR_TMPL - scalarref)
185 csrf_error_tmpl_param : CSRF error display html parameter (for HTML::Template)
186 csrf_id : CSRF ticket name (default: _csrf_id)
187 csrf_post_only : CSRF protect runmode request method check(default:0 1:POST Only)
188  
189 Example:
190  
191 sub cgiapp_init {
192 my $self = shift;
193 $self->tmpl_path("/path/to/template");
194 $self->protect_csrf_config(
195 csrf_error_status => 403, # change forbidden
196 csrf_error_tmpl => "csrf_error.tmpl",
197 csrf_error_tmpl_param => { TITLE => "CSRF ERROR", MESSAGE => "your access is csrf!"},
198 csrf_id => "ticket_id",
199 csrf_post_only => 1
200 );
201 }
202  
203 # csrf_error.tmpl
204 <html><head><title><TMPL_VAR NAME=TITLE ESCAPE=HTML></title></head>
205 <body>
206 <h1>CSRF Error</h1>
207 <span style="color: red"><TMPL_VAR NAME=MESSAGE ESCAPE=HTML></span>
208 </body>
209 </html>
210  
211 =cut
212  
213 4 ▶sub protect_csrf_config {
Subroutine protect_csrf_config: called CC=9 SCAR=24.4
Pod documented
214  
215 4 my($self, %args) = @_;
216 4 ▶ if(ref($self->{__CAP_PROTECT_CSRF_CONFIG}) ne "HASH"){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"__CAP_PROTECT_CSRF_CONFIG"} ne "HASH") 4 0 4
217 4 $self->{__CAP_PROTECT_CSRF_CONFIG} = {};
218 }
219  
220 4 ▶ $self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_status} = exists $args{csrf_error_status} ? $args{csrf_error_status} : $CSRF_ERROR_STATUS;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'csrf_error_status'} ? : 0 4 4
221 4 ▶ $self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_mode} = exists $args{csrf_error_mode} ? $args{csrf_error_mode} : $CSRF_ERROR_MODE;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'csrf_error_mode'} ? : 0 4 4
222 4 ▶ $self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_tmpl} = exists $args{csrf_error_tmpl} ? $args{csrf_error_tmpl} : $CSRF_ERROR_TMPL;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'csrf_error_tmpl'} ? : 4 0 4
223 4 $self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_tmpl_param} = {};
224 4 ▶ $self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_id} = exists $args{csrf_id} ? $args{csrf_id} : $CSRF_ID;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'csrf_id'} ? : 0 4 4
225 4 ▶ $self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_post_only} = exists $args{csrf_post_only} ? $args{csrf_post_only} : $CSRF_POST_ONLY;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'csrf_post_only'} ? : 0 4 4
226  
227 4 ▶ if(ref($args{csrf_error_tmpl_param}) eq "HASH" && keys %{$args{csrf_error_tmpl_param}}){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args{"csrf_error_tmpl_param"} eq "HASH" and keys %{$args{"csrf_error_tmpl_param"};}) 4 0 4
Condition33%1/3
ref $args{"csrf_error_tmpl_param"} eq "HASH" and keys %{$args{"csrf_error_tmpl_param"};}
!ll&&!rl&&r
004
MC/DC0%0/2
ref $args{"csrf_error_tmpl_param"} eq "HASH" and keys %{$args{"csrf_error_tmpl_param"};}
ref $args{"csrf_error_tmpl_param"} eq "HASH" keys %{$args{"csrf_error_tmpl_param"};}
Truth table33%1/3
A and B
A= ref $args{"csrf_error_tmpl_param"} eq "HASH"B= keys %{$args{"csrf_error_tmpl_param"};}
ABresult
0X0
100
111
228 4 $self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_tmpl_param} = $args{csrf_error_tmpl_param};
229 }
230 }
231  
232 =pod
233  
234 =head2 clear_csrf_id
235  
236 Clear csrfid. It is preferable to make it execute after processing ends.
237  
238 Example :
239  
240 sub cgiapp_init {
241 my $self = shift;
242 $self->protect_csrf_config;
243 }
244  
245 sub input {
246 my $self = shift;
247 do_something(). # input form display..
248 }
249
250 sub confirm : PublishCSRFID {
251 my $self = shift;
252 do_something(). # publish csrf_id and input check and confirm display..
253 }
254  
255 sub complete : ProtectCSRF {
256 my $self = shift;
257 $self->clear_csrf_id(1); # clear csrf_id for CSRF protect
258 do_something(); # DB insert etc..
259 }
260  
261 =cut
262  
263 1 ▶sub clear_csrf_id {
Subroutine clear_csrf_id: called CC=2 SCAR=7.1
Pod documented
264  
265 1 my($self, $fast) = @_;
266 1 $self->session->clear($self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_id});
267 1 ▶ $self->session->flush if $fast;
Branch: 1 branch
BranchTrueFalseTotal
if $fast 1 0 1
268 }
269  
270 =pod
271  
272 =head1 CALLBACK
273  
274 =head2 _publish_csrf_id
275  
276 prerun callback
277  
278 =cut
279  
280 4 ▶sub _publish_csrf_id {
Subroutine _publish_csrf_id: called CC=3 SCAR=11.1
281  
282 4 my($self, $rm) = @_;
283 4 ▶ return if !exists $publish_csrf_id_runmodes{$self->can($rm)};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $publish_csrf_id_runmodes{$self->can($rm)} 3 1 4
284  
285 1 ▶ if(ref($self->{__CAP_PROTECT_CSRF_CONFIG}) ne "HASH"){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"__CAP_PROTECT_CSRF_CONFIG"} ne "HASH") 0 1 1
286 0 $self->protect_csrf_config;
287 }
288  
289 1 my @words = ('A'..'Z', 'a'..'z', 0..9, '/', '.');
290 1 my $salt = join "", @words[ map { sprintf( "%d", rand(scalar @words) ) } 1..2 ];
291 1 my $csrf_id = sha1_hex($salt . time . $$ . rand(10000));
292 1 $self->session->param($self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_id}, $csrf_id);
293 }
294  
295 =pod
296  
297 =head2 _csrf_forbidden
298  
299 prerun callback
300  
301 =cut
302  
303 4 ▶sub _csrf_forbidden {
Subroutine _csrf_forbidden: called CC=9 SCAR=22.6
304  
305 4 my($self, $rm) = @_;
306 4 my $err_flg = 0;
307  
308 4 ▶ return if !exists $protect_csrf_runmodes{$self->can($rm)};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $protect_csrf_runmodes{$self->can($rm)} 1 3 4
309  
310 3 ▶ if(ref($self->{__CAP_PROTECT_CSRF_CONFIG}) ne "HASH"){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"__CAP_PROTECT_CSRF_CONFIG"} ne "HASH") 0 3 3
311 0 $self->protect_csrf_config;
312 }
313  
314 3 ▶ if($self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_post_only} && $ENV{REQUEST_METHOD} ne "POST"){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'__CAP_PROTECT_CSRF_CONFIG'}{'csrf_post_only'} and $ENV{'REQUEST_METHOD'} ne 'POST') { } 0 3 3
Condition33%1/3
$self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_post_only"} and $ENV{"REQUEST_METHOD"} ne "POST"
!ll&&!rl&&r
300
MC/DC0%0/2
$self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_post_only"} and $ENV{"REQUEST_METHOD"} ne "POST"
$self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_post_only"} $ENV{"REQUEST_METHOD"} ne "POST"
Truth table33%1/3
A and B
A= $self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_post_only"}B= $ENV{"REQUEST_METHOD"} ne "POST"
ABresult
0X0
100
111
315 0 $err_flg = 1;
316 } else {
317  
318 3 ▶ if(
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->query->param($self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_id"}) && $self->csrf_id or $self->query->param($self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_id"}) ne $self->csrf_id) 2 1 3
Condition83%5/6
not $self->query->param($self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_id"}) && $self->csrf_id or $self->query->param($self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_id"}) ne $self->csrf_id
l!l&&r!l&&!r
201
$self->query->param($self->{'__CAP_PROTECT_CSRF_CONFIG'}{'csrf_id'}) && $self->csrf_id
!ll&&!rl&&r
111
MC/DC66%2/3
not $self->query->param($self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_id"}) && $self->csrf_id or $self->query->param($self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_id"}) ne $self->csrf_id
$self->query->param($self->{'__CAP_PROTECT_CSRF_CONFIG'}{'csrf_id'}) $self->csrf_id $self->query->param($self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_id"}) ne $self->csrf_id
Truth table75%3/4
not(A && B) or C
A= $self->query->param($self->{'__CAP_PROTECT_CSRF_CONFIG'}{'csrf_id'})B= $self->csrf_idC= $self->query->param($self->{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_id"}) ne $self->csrf_id
ABCresult
0XX1
10X1
1111
1100
319 !$self->query->param($self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_id}) ||
320 !$self->csrf_id ||
321 $self->query->param($self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_id}) ne $self->csrf_id
322 ){
323 2 $err_flg = 1;
324 }
325 }
326  
327 3 ▶ if($err_flg){
Branch: 1 branch
BranchTrueFalseTotal
if ($err_flg) 2 1 3
328  
329 2 ▶ $self->run_modes( $self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_mode} => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
330
331 2 my $self = shift;
332 2 $self->header_props( -type => "text/html", -status => $self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_status} );
333  
334 2 my $tmpl_obj = $self->load_tmpl($self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_tmpl}, die_on_bad_params => 0);
335 2 ▶ if(keys %{$self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_tmpl_param}}){
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$$self{"__CAP_PROTECT_CSRF_CONFIG"}{"csrf_error_tmpl_param"};}) 2 0 2
336 2 $tmpl_obj->param(%{$self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_tmpl_param}});
337 }
338 2 return $tmpl_obj->output;
339 2 });
340 2 $self->prerun_mode($self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_error_mode});
341 }
342  
343 3 return 0;
344 }
345  
346  
347 =pod
348  
349 =head2 _add_csrf_id
350  
351 postrun callback
352  
353 =cut
354  
355 4 ▶sub _add_csrf_id {
Subroutine _add_csrf_id: called CC=9 SCAR=22.4
356  
357 4 my($self, $scalarref) = @_;
358 4 my $rm = $self->get_current_runmode;
359 4 my $coderef = $self->can($rm);
360 4 ▶ return if !$coderef || !exists $publish_csrf_id_runmodes{$coderef};
Branch: 1 branch
BranchTrueFalseTotal
unless $coderef and exists $publish_csrf_id_runmodes{$coderef} 3 1 4
Condition100%3/3
$coderef and exists $publish_csrf_id_runmodes{$coderef}
!ll&&!rl&&r
211
MC/DC100%2/2
$coderef and exists $publish_csrf_id_runmodes{$coderef}
$coderef exists $publish_csrf_id_runmodes{$coderef}
Truth table100%3/3
A and B
A= $coderefB= exists $publish_csrf_id_runmodes{$coderef}
ABresult
0X0
100
111
361  
362 1 ▶ if(ref($self->{__CAP_PROTECT_CSRF_CONFIG}) ne "HASH"){
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"__CAP_PROTECT_CSRF_CONFIG"} ne "HASH") 0 1 1
363 0 $self->protect_csrf_config;
364 }
365  
366 # my %header = $self->header_props;
367 # return if %header && $header{-type} ne "text/html";
368  
369 1 my $body = "";
370 1 my $hidden = sprintf qq{<input type="hidden" name="%s" value="%s" />}, $self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_id}, $self->csrf_id;
371  
372 1 my $parser = HTML::TokeParser->new($scalarref);
373 1 ▶ while(my $token = $parser->get_token){
Branch: 1 branch
BranchTrueFalseTotal
if (my $token = $parser->get_token) 4 1 5
374  
375 # start tag(<form> sniping)
376 4 ▶ if($token->[0] eq "S"){
Branch: 3 branches
BranchTrueFalseTotal
if ($token->[0] eq 'S') { } 3 1 4
elsif ($token->[0] =~ /^(E|PI)$/) { } 1 0 1
elsif ($token->[0] =~ /^(T|C|D)$/) { } 0 0 0
377
378 3 ▶ if(lc($token->[1]) eq "form"){
Branch: 1 branch
BranchTrueFalseTotal
if (lc $token->[1] eq 'form') { } 1 2 3
379 1 $body .= $token->[4] . "\n" . $hidden;
380 # In the future...
381 #}elsif(lc($token->[1]) eq "a"){
382 #
383 # if(exists $token->[2]->{href} && defined $token->[2]->{href}){
384 # my $uri = URI->new($token->[2]->{href});
385 # my %query_form = $uri->query_form;
386 # $query_form{$self->{__CAP_PROTECT_CSRF_CONFIG}->{csrf_id}} = $self->csrf_id;
387 # $uri->query_form(%query_form);
388 # $token->[2]->{href} = $uri->path_query;
389 # my $prop = join " ", (map { $_ . "=\"" . $token->[2]->{$_} . "\"" } keys %{$token->[2]});
390 # $body .= "<" . lc($token->[1]) . " ". $prop . ">";
391 # }else{
392 # $body .= $token->[4];
393 # }
394  
395 }else{
396 2 $body .= $token->[4];
397 }
398  
399 # end tag, process instructions
400 }elsif($token->[0] =~ /^(E|PI)$/){
401 1 $body .= $token->[2];
402
403 # text, comment, declaration
404 }elsif($token->[0] =~ /^(T|C|D)$/){
405 0 $body .= $token->[1];
406 }
407 }
408  
409 1 ${$scalarref} = $body;
410 }
411  
412 5 1;
413  
414 __END__
↑ Summary