blib/lib/Perl/Critic/Policy/ValuesAndExpressions/PreventSQLInjection.pm

filter: Statementstmt 97.9% 191 / 195 Branchbran 88.3% 106 / 120 Conditioncond 75.3% 55 / 73 MC/DCmcdc 60.0% 27 / 45 Subroutinesub 96.4% 27 / 28 Podpod 100% 16 / 16 totaltotal 88.4% 422 / 477 CC 88 SCAR 23.7
CC
88
Cov
91%
detect_sql_injections
21.0
get_function_name
16.3
__ANON__
14.1
CRAP 10.7
↑ Summary
1 package Perl::Critic::Policy::ValuesAndExpressions::PreventSQLInjection;
2  
3 12 ▶use 5.006001;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 12 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 12 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 12 our $VERSION = '2.000001';
8  
9 12 ▶use base 'Perl::Critic::Policy';
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 12 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 12 ▶use Perl::Critic::Utils qw( $TRUE );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 12 ▶use PPIx::QuoteLike 0.015 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 12 ▶use Readonly ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 12 ▶use String::InterpolatedVariables ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 12 ▶use Try::Tiny qw( catch try );
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18  
19 12 Readonly::Scalar my $DESCRIPTION => 'SQL injection risk.';
20 12 Readonly::Scalar my $EXPLANATION =>
21 'Variables in interpolated SQL string are susceptible to SQL injection: %s';
22  
23 # Default for the name of the methods that make a variable safe to use in SQL
24 # strings.
25 12 Readonly::Scalar my $QUOTING_METHODS_DEFAULT => q|
26 quote_identifier
27 quote
28 |;
29  
30 # Default for the name of the packages and functions / class methods that are safe to
31 # concatenate to SQL strings.
32 12 Readonly::Scalar my $SAFE_FUNCTIONS_DEFAULT => q|
33 |;
34  
35 # Default for the name of the functions that are generally safe to use (because they
36 # are not expected to generate SQL calls -- unless you are doing something really,
37 # really weird.)
38 12 Readonly::Scalar my $SAFE_CONTEXT_DEFAULT => q|
39 die
40 warn
41 carp
42 croak
43 confess
44 |;
45  
46 # Regex to detect comments like ## SQL safe ($var1, $var2).
47 12 Readonly::Scalar my $SQL_SAFE_COMMENTS_REGEX => qr/
48 \A
49 (?: [#]! .*? )?
50 \s*
51 # Find the ## annotation starter.
52 [#][#]
53 \s*
54 # "SQL safe" is our keyword.
55 SQL \s+ safe
56 \s*
57 # List of safe variables between parentheses.
58 \(\s*(.*?)\s*\)
59 /ixms;
60  
61  
62 75 ▶sub supported_parameters {
Subroutine supported_parameters: called CC=1 SCAR=0.0
Pod documented
63 return (
64 {
65 75 name => 'quoting_methods',
66 description =>
67 'A space-separated string listing the methods that return a safely quoted value.',
68 default_string => $QUOTING_METHODS_DEFAULT,
69 behavior => 'string',
70 },
71 {
72 name => 'safe_functions',
73 description =>
74 'A space-separated string listing the functions that return a safely quoted value',
75 default_string => $SAFE_FUNCTIONS_DEFAULT,
76 behavior => 'string',
77 },
78 {
79 name => 'safe_context',
80 description =>
81 'A space-separated string listing the functions that are not subject to SQL injections',
82 default_string => $SAFE_CONTEXT_DEFAULT,
83 behavior => 'string',
84 },
85 {
86 name => 'prefer_upper_case_keywords',
87 description =>
88 'Match on SELECT, UPDATE, INSERT, DELETE but not on their lower or mixed case variants',
89 default_string => '0',
90 behavior => 'boolean',
91 },
92 );
93 }
94  
95  
96 36 ▶sub default_severity {
Subroutine default_severity: called CC=1 SCAR=0.0
Pod documented
97 36 return $Perl::Critic::Utils::SEVERITY_HIGHEST;
98 }
99  
100  
101 1 ▶sub default_themes {
Subroutine default_themes: called CC=1 SCAR=0.0
Pod documented
102 1 return qw( security );
103 }
104  
105  
106 75 ▶sub applies_to {
Subroutine applies_to: called CC=1 SCAR=0.0
Pod documented
107 75 return qw(
108 PPI::Token::Quote
109 PPI::Token::HereDoc
110 );
111 }
112  
113  
114 75 ▶sub prepare_to_scan_document {
Subroutine prepare_to_scan_document: called CC=1 SCAR=0.0
Pod documented
115 75 my $self = shift;
116 75 delete $self->{'_sqlsafe'};
117 75 return $TRUE;
118 }
119  
120  
121 116 ▶sub violates {
Subroutine violates: called CC=5 SCAR=16.1
Pod documented
122 116 my ( $self, $element, $doc ) = @_;
123  
124 116 parse_config_parameters($self);
125  
126 116 parse_comments( $self, $doc );
127  
128 # Make sure the first string looks like a SQL statement before investigating
129 # further.
130 return ()
131 116 ▶ if !$self->is_sql_statement($element);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_sql_statement($element) 37 79 116
132  
133 # Skip this statement if we are in a safe context (e.g., die "string")
134 return ()
135 79 ▶ if $self->is_in_safe_context($element);
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_in_safe_context($element) 10 69 79
136  
137 # Find SQL injection vulnerabilities.
138 69 my $sql_injections = detect_sql_injections( $self, $element );
139  
140 # Return violations if any.
141 69 ▶ return defined($sql_injections) && scalar(@$sql_injections) != 0
Branch: 1 branch
BranchTrueFalseTotal
defined $sql_injections && scalar @$sql_injections != 0 ? : 36 33 69
Condition66%2/3
defined $sql_injections and scalar @$sql_injections != 0
!ll&&!rl&&r
03336
MC/DC50%1/2
defined $sql_injections and scalar @$sql_injections != 0
defined $sql_injections scalar @$sql_injections != 0
Truth table66%2/3
A and B
A= defined $sql_injectionsB= scalar @$sql_injections != 0
ABresult
0X0
100
111
142 ? $self->violation(
143 $DESCRIPTION,
144 sprintf(
145 $EXPLANATION,
146 join( ', ', @$sql_injections ),
147 ),
148 $element,
149 )
150 : ();
151 }
152  
153  
154 69 ▶sub detect_sql_injections {
Subroutine detect_sql_injections: called CC=21 SCAR=30.5
Pod documented
155 69 my ( $self, $element ) = @_;
156  
157 69 my $sql_injections = [];
158 69 my $token = $element;
159 69 ▶ while ( defined($token) && $token ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $token and $token ne "") 336 9 345
Condition66%2/3
defined $token and $token ne ""
!ll&&!rl&&r
09336
MC/DC50%1/2
defined $token and $token ne ""
defined $token $token ne ""
Truth table66%2/3
A and B
A= defined $tokenB= $token ne ""
ABresult
0X0
100
111
160 ## no critic (ControlStructures::ProhibitCascadingIfElse)
161  
162 # If the token is a string, we need to analyze it for interpolated
163 # variables.
164 336 ▶ if ( $token->isa('PPI::Token::HereDoc')
Branch: 7 branches
BranchTrueFalseTotal
if ($token->isa('PPI::Token::HereDoc') or $token->isa('PPI::Token::Quote')) { } 93 243 336
elsif ($token->isa('PPI::Token::Operator') and $token->content eq '.') { } 61 182 243
elsif ($token->isa('PPI::Token::Structure') and $token->content eq ';') { } 56 126 182
elsif ($token->isa('PPI::Token::Operator') and $token->content eq ':') { } 3 123 126
elsif ($token->isa('PPI::Token::Operator') and $token->content eq ',') { } 1 122 123
elsif ($token->isa('PPI::Token::Symbol')) { } 25 97 122
elsif ($token->isa('PPI::Token::Word')) { } 25 72 97
Condition100%3/3
$token->isa("PPI::Token::HereDoc") or $token->isa("PPI::Token::Quote")
l!l&&r!l&&!r
1083243
MC/DC100%2/2
$token->isa("PPI::Token::HereDoc") or $token->isa("PPI::Token::Quote")
$token->isa("PPI::Token::HereDoc") $token->isa("PPI::Token::Quote")
Truth table100%3/3
A or B
A= $token->isa("PPI::Token::HereDoc")B= $token->isa("PPI::Token::Quote")
ABresult
1X1
011
000
165 || $token->isa('PPI::Token::Quote')
166 ) ## no critic (ControlStructures::ProhibitCascadingIfElse)
167 {
168 push(
169 @$sql_injections,
170 93 ▶ @{ analyze_string_injections( $self, $token ) || [] }
Condition50%1/2
analyze_string_injections($self, $token) || []
l!l
930
MC/DC0%0/1
analyze_string_injections($self, $token) || []
analyze_string_injections($self, $token)
Truth table50%1/2
A
A= analyze_string_injections($self, $token)
Aresult
11
00
171 );
172 }
173  
174 # If it is a concatenation operator, continue to the next token.
175 ▶ elsif ($token->isa('PPI::Token::Operator')
Condition100%3/3
$token->isa("PPI::Token::Operator") and $token->content eq "."
!ll&&!rl&&r
1493361
MC/DC100%2/2
$token->isa("PPI::Token::Operator") and $token->content eq "."
$token->isa("PPI::Token::Operator") $token->content eq "."
Truth table100%3/3
A and B
A= $token->isa("PPI::Token::Operator")B= $token->content eq "."
ABresult
0X0
100
111
176 && $token->content() eq '.' ) {
177  
178 # Skip to the next token.
179 }
180  
181 # If it is a semicolon, we're at the end of the statement and we can finish
182 # the process.
183 ▶ elsif ($token->isa('PPI::Token::Structure')
Condition66%2/3
$token->isa("PPI::Token::Structure") and $token->content eq ";"
!ll&&!rl&&r
126056
MC/DC50%1/2
$token->isa("PPI::Token::Structure") and $token->content eq ";"
$token->isa("PPI::Token::Structure") $token->content eq ";"
Truth table66%2/3
A and B
A= $token->isa("PPI::Token::Structure")B= $token->content eq ";"
ABresult
0X0
100
111
184 && $token->content() eq ';' ) {
185 56 last;
186 }
187  
188 # If we detect a ':' operator, we're at the end of the second argument in a
189 # ternary "... ? ... : ..." and we need to finish the process here as the
190 # third argument is not concatenated to the this string and will be
191 # analyzed separately.
192 ▶ elsif ($token->isa('PPI::Token::Operator')
Condition100%3/3
$token->isa("PPI::Token::Operator") and $token->content eq ":"
!ll&&!rl&&r
93303
MC/DC100%2/2
$token->isa("PPI::Token::Operator") and $token->content eq ":"
$token->isa("PPI::Token::Operator") $token->content eq ":"
Truth table100%3/3
A and B
A= $token->isa("PPI::Token::Operator")B= $token->content eq ":"
ABresult
0X0
100
111
193 && $token->content() eq ':' ) {
194 3 last;
195 }
196  
197 # If it is a list-separating comma, this list element ends here and we can
198 # finish the process.
199 ▶ elsif ($token->isa('PPI::Token::Operator')
Condition100%3/3
$token->isa("PPI::Token::Operator") and $token->content eq ","
!ll&&!rl&&r
93291
MC/DC100%2/2
$token->isa("PPI::Token::Operator") and $token->content eq ","
$token->isa("PPI::Token::Operator") $token->content eq ","
Truth table100%3/3
A and B
A= $token->isa("PPI::Token::Operator")B= $token->content eq ","
ABresult
0X0
100
111
200 && $token->content() eq ',' ) {
201 1 last;
202 }
203  
204 # If it is a symbol, it is concatenated to a SQL statement which is an
205 # injection risk.
206 elsif ( $token->isa('PPI::Token::Symbol') ) {
207 25 my ( $variable, $is_quoted )
208 = get_complete_variable( $self, $token );
209 25 ▶ if ( !$is_quoted ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_quoted) 19 6 25
210 19 my $safe_elements
211 = get_safe_elements( $self, $token->line_number() );
212 push( @$sql_injections, $variable )
213 19 ▶ if !exists( $safe_elements->{$variable} );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $safe_elements->{$variable} 13 6 19
214 }
215 }
216  
217 # If it is a word, it may be a function/method call on a package, which is
218 # an injection risk.
219 elsif ( $token->isa('PPI::Token::Word') ) {
220  
221 # Find out if the PPO::Token::Word is the beginning of a call or not.
222 25 my ( $function_name, $is_quoted )
223 = get_function_name( $self, $token );
224 25 ▶ if ( defined($function_name) && !$is_quoted ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $function_name and not $is_quoted) 9 16 25
Condition100%3/3
defined $function_name and not $is_quoted
!ll&&!rl&&r
1519
MC/DC100%2/2
defined $function_name and not $is_quoted
defined $function_name not $is_quoted
Truth table100%3/3
A and not(B)
A= defined $function_nameB= not $is_quoted
ABresult
0X0
100
111
225 9 my $safe_elements
226 = get_safe_elements( $self, $token->line_number() );
227 push( @$sql_injections, $function_name )
228 9 ▶ if !exists( $safe_elements->{ '&' . $function_name } );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$safe_elements{'&' . $function_name} 4 5 9
229 }
230 }
231  
232 # Move to examining the next sibling token.
233 276 $token = $token->snext_sibling();
234 }
235  
236 69 return $sql_injections;
237 }
238  
239  
240 25 ▶sub get_function_name {
Subroutine get_function_name: called CC=15 SCAR=27.9
Pod documented
241 25 my ( $self, $token ) = @_;
242  
243 25 ▶ croak 'The first parameter needs to be a PPI::Token::Word object'
Branch: 1 branch
BranchTrueFalseTotal
unless $token->isa("PPI::Token::Word") 0 25 25
244 if !$token->isa('PPI::Token::Word');
245  
246 25 my $next_sibling = $token->snext_sibling();
247 return ()
248 25 ▶ if !defined($next_sibling) || ( $next_sibling eq '' );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $next_sibling or $next_sibling eq "" 0 25 25
Condition33%1/3
not defined $next_sibling or $next_sibling eq ""
l!l&&r!l&&!r
0025
MC/DC0%0/2
not defined $next_sibling or $next_sibling eq ""
not defined $next_sibling $next_sibling eq ""
Truth table33%1/3
not(A) or B
A= not defined $next_siblingB= $next_sibling eq ""
ABresult
1X1
011
000
249  
250 25 my ( $package, $function_name );
251  
252 # Catch Package::Name->method().
253 25 ▶ if ( $next_sibling->isa('PPI::Token::Operator')
Branch: 2 branches
BranchTrueFalseTotal
if ($next_sibling->isa('PPI::Token::Operator') and $next_sibling->content eq '->') { } 6 19 25
elsif ($next_sibling->isa('PPI::Structure::List')) { } 18 1 19
Condition66%2/3
$next_sibling->isa("PPI::Token::Operator") and $next_sibling->content eq "->"
!ll&&!rl&&r
1906
MC/DC50%1/2
$next_sibling->isa("PPI::Token::Operator") and $next_sibling->content eq "->"
$next_sibling->isa("PPI::Token::Operator") $next_sibling->content eq "->"
Truth table66%2/3
A and B
A= $next_sibling->isa("PPI::Token::Operator")B= $next_sibling->content eq "->"
ABresult
0X0
100
111
254 && ( $next_sibling->content() eq '->' ) ) {
255 6 my $function = $next_sibling->snext_sibling();
256  
257 return ()
258 6 ▶ if !defined($function) || ( $function eq '' );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $function or $function eq "" 0 6 6
Condition33%1/3
not defined $function or $function eq ""
l!l&&r!l&&!r
006
MC/DC0%0/2
not defined $function or $function eq ""
not defined $function $function eq ""
Truth table33%1/3
not(A) or B
A= not defined $functionB= $function eq ""
ABresult
1X1
011
000
259 return ()
260 6 ▶ if !$function->isa('PPI::Token::Word');
Branch: 1 branch
BranchTrueFalseTotal
unless $function->isa("PPI::Token::Word") 2 4 6
261  
262 4 $package = $token->content();
263 4 $function_name = $function->content();
264  
265 4 $function->{'_handled'} = 1;
266 }
267  
268 # Catch Package::Name::function().
269 elsif ( $next_sibling->isa('PPI::Structure::List') ) {
270  
271 # Package::Name->method() will result in two PPI::Token::Word being
272 # detected, one for 'Package::Name' and one for 'method'. 'Package::Name'
273 # will be caught in the if() block above, but 'method' would get caught
274 # separately by this block. To prevent this, we scan the previous sibling
275 # here and skip if we find that it is a '->' operator.
276 18 my $previous_sibling = $token->sprevious_sibling();
277 return ()
278 18 ▶ if $previous_sibling->isa('PPI::Token::Operator')
Branch: 1 branch
BranchTrueFalseTotal
if $previous_sibling->isa("PPI::Token::Operator") and $previous_sibling->content eq "->" 12 6 18
Condition66%2/3
$previous_sibling->isa("PPI::Token::Operator") and $previous_sibling->content eq "->"
!ll&&!rl&&r
0612
MC/DC50%1/2
$previous_sibling->isa("PPI::Token::Operator") and $previous_sibling->content eq "->"
$previous_sibling->isa("PPI::Token::Operator") $previous_sibling->content eq "->"
Truth table66%2/3
A and B
A= $previous_sibling->isa("PPI::Token::Operator")B= $previous_sibling->content eq "->"
ABresult
0X0
100
111
279 && ( $previous_sibling->content() eq '->' );
280  
281 6 my $content = $token->content();
282  
283 # Catch function calls in the same namespace.
284 6 ▶ if ( $content !~ /::/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $content =~ /::/) { } 3 3 6
285 3 ( $package, $function_name ) = ( undef, $content );
286 }
287  
288 # Catch function calls in a different namespace.
289 else {
290 3 ( $package, $function_name ) = $content =~ /^(.*)::([^:]+)$/;
291 }
292 }
293 else {
294 1 return ();
295 }
296  
297 my $full_name
298 10 = join( '::', grep { defined($_) } ( $package, $function_name ) );
299 my $is_safe
300 = defined( $self->{'_safe_functions_regex'} )
301 10 ▶ && ( $full_name =~ $self->{'_safe_functions_regex'} )
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'_safe_functions_regex'} && $full_name =~ /$self->{'_safe_functions_regex'}/ ? : 1 9 10
Condition66%2/3
defined $self->{"_safe_functions_regex"} and $full_name =~ /$self->{"_safe_functions_regex"}/
!ll&&!rl&&r
901
MC/DC50%1/2
defined $self->{"_safe_functions_regex"} and $full_name =~ /$self->{"_safe_functions_regex"}/
defined $self->{"_safe_functions_regex"} $full_name =~ /$self->{"_safe_functions_regex"}/
Truth table66%2/3
A and B
A= defined $self->{"_safe_functions_regex"}B= $full_name =~ /$self->{"_safe_functions_regex"}/
ABresult
0X0
100
111
302 ? 1
303 : 0;
304 10 return ( $full_name, $is_safe );
305 }
306  
307  
308 25 ▶sub get_complete_variable {
Subroutine get_complete_variable: called CC=11 SCAR=24.3
Pod documented
309 25 my ( $self, $token ) = @_;
310  
311 25 ▶ croak 'The first parameter needs to be a PPI::Token::Symbol object'
Branch: 1 branch
BranchTrueFalseTotal
unless $token->isa("PPI::Token::Symbol") 0 25 25
312 if !$token->isa('PPI::Token::Symbol');
313  
314 25 my $variable = $token->content();
315 25 my $is_quoted = 0;
316 25 my $sibling = $token;
317 25 while (1) {
318 64 $sibling = $sibling->next_sibling();
319 64 ▶ last if !defined($sibling) || ( $sibling eq '' );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $sibling or $sibling eq "" 0 64 64
Condition33%1/3
not defined $sibling or $sibling eq ""
l!l&&r!l&&!r
0064
MC/DC0%0/2
not defined $sibling or $sibling eq ""
not defined $sibling $sibling eq ""
Truth table33%1/3
not(A) or B
A= not defined $siblingB= $sibling eq ""
ABresult
1X1
011
000
320  
321 64 ▶ if ( $sibling->isa('PPI::Token::Operator')
Branch: 3 branches
BranchTrueFalseTotal
if ($sibling->isa('PPI::Token::Operator') and $sibling->content eq '->') { } 22 42 64
elsif ($sibling->isa('PPI::Structure::Subscript')) { } 17 25 42
elsif ($sibling->isa('PPI::Token::Word') and $sibling->method_call and defined $self->{'_quoting_methods_regex'} and $sibling->content =~ /$self->{'_quoting_methods_regex'}/) { } 6 19 25
Condition66%2/3
$sibling->isa("PPI::Token::Operator") and $sibling->content eq "->"
!ll&&!rl&&r
42022
MC/DC50%1/2
$sibling->isa("PPI::Token::Operator") and $sibling->content eq "->"
$sibling->isa("PPI::Token::Operator") $sibling->content eq "->"
Truth table66%2/3
A and B
A= $sibling->isa("PPI::Token::Operator")B= $sibling->content eq "->"
ABresult
0X0
100
111
322 && $sibling->content() eq '->' ) {
323 22 $variable .= '->';
324 }
325 elsif ( $sibling->isa('PPI::Structure::Subscript') ) {
326 17 $variable .= $sibling->content();
327 }
328 ▶ elsif ($sibling->isa('PPI::Token::Word')
Condition88%8/9
$sibling->isa("PPI::Token::Word") and $sibling->method_call and defined $self->{"_quoting_methods_regex"} and $sibling->content =~ /$self->{"_quoting_methods_regex"}/
!ll&&!rl&&r
1816
$sibling->isa("PPI::Token::Word") and $sibling->method_call and defined $self->{"_quoting_methods_regex"}
!ll&&!rl&&r
1717
$sibling->isa("PPI::Token::Word") and $sibling->method_call
!ll&&!rl&&r
1708
MC/DC75%3/4
$sibling->isa("PPI::Token::Word") and $sibling->method_call and defined $self->{"_quoting_methods_regex"} and $sibling->content =~ /$self->{"_quoting_methods_regex"}/
$sibling->isa("PPI::Token::Word") $sibling->method_call defined $self->{"_quoting_methods_regex"} $sibling->content =~ /$self->{"_quoting_methods_regex"}/
Truth table80%4/5
A and B and C and D
A= $sibling->isa("PPI::Token::Word")B= $sibling->method_callC= defined $self->{"_quoting_methods_regex"}D= $sibling->content =~ /$self->{"_quoting_methods_regex"}/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
329 && $sibling->method_call()
330 && defined( $self->{'_quoting_methods_regex'} )
331 && ( $sibling->content =~ $self->{'_quoting_methods_regex'} ) ) {
332 6 $is_quoted = 1;
333 6 last;
334 }
335 else {
336 19 last;
337 }
338 }
339  
340 25 return ( $variable, $is_quoted );
341 }
342  
343  
344 116 ▶sub is_sql_statement {
Subroutine is_sql_statement: called CC=6 SCAR=17.9
Pod documented
345 116 my ( $self, $token ) = @_;
346  
347 116 my $probably_sql = 0;
348 116 ▶ if ( $token->isa('PPI::Token::HereDoc')
Branch: 1 branch
BranchTrueFalseTotal
if ($token->isa("PPI::Token::HereDoc") and $token eq "<<\"SQL\"" || $token eq "<<SQL") 4 112 116
Condition100%6/6
$token->isa("PPI::Token::HereDoc") and $token eq "<<\"SQL\"" || $token eq "<<SQL"
!ll&&!rl&&r
10484
$token eq "<<\"SQL\"" or $token eq "<<SQL"
l!l&&r!l&&!r
138
MC/DC100%3/3
$token->isa("PPI::Token::HereDoc") and $token eq "<<\"SQL\"" || $token eq "<<SQL"
$token->isa("PPI::Token::HereDoc") $token eq "<<\"SQL\"" $token eq "<<SQL"
Truth table100%4/4
A and B or C
A= $token->isa("PPI::Token::HereDoc")B= $token eq "<<\"SQL\""C= $token eq "<<SQL"
ABCresult
0XX0
1000
11X1
1011
349 && ( $token eq q{<<"SQL"} || $token eq q{<<SQL} ) ) {
350 4 $probably_sql = 1;
351 }
352  
353 116 my $content = get_token_content($token);
354  
355 116 ▶ if ( !$probably_sql && $self->{_prefer_upper_case_keywords} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $probably_sql and $self->{"_prefer_upper_case_keywords"}) 2 114 116
Condition100%3/3
not $probably_sql and $self->{"_prefer_upper_case_keywords"}
!ll&&!rl&&r
41102
MC/DC100%2/2
not $probably_sql and $self->{"_prefer_upper_case_keywords"}
not $probably_sql $self->{"_prefer_upper_case_keywords"}
Truth table100%3/3
not(A) and B
A= not $probably_sqlB= $self->{"_prefer_upper_case_keywords"}
ABresult
0X0
100
111
356 2 return $content
357 =~ m{^ \s* (?: SELECT | INSERT | UPDATE | DELETE | ALTER | DROP | CREATE ) \b}sx;
358 }
359  
360 114 return $content
361 =~ m{^ \s* (?: SELECT | INSERT | UPDATE | DELETE | ALTER | DROP | CREATE ) \b}six;
362 }
363  
364  
365 79 ▶sub is_in_safe_context {
Subroutine is_in_safe_context: called CC=5 SCAR=16.2
Pod documented
366 79 my ( $self, $token ) = @_;
367  
368 79 ▶ return 0 if !$self->{'_safe_context_regex'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_safe_context_regex"} 0 79 79
369  
370 79 my $sprevious_sibling = $token->sprevious_sibling;
371  
372 79 ▶ return 0 if !defined $sprevious_sibling || $sprevious_sibling eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $sprevious_sibling or $sprevious_sibling eq "" 1 78 79
Condition66%2/3
not defined $sprevious_sibling or $sprevious_sibling eq ""
l!l&&r!l&&!r
0178
MC/DC50%1/2
not defined $sprevious_sibling or $sprevious_sibling eq ""
not defined $sprevious_sibling $sprevious_sibling eq ""
Truth table66%2/3
not(A) or B
A= not defined $sprevious_siblingB= $sprevious_sibling eq ""
ABresult
1X1
011
000
373 78 ▶ return 0 if !$sprevious_sibling->isa('PPI::Token::Word');
Branch: 1 branch
BranchTrueFalseTotal
unless $sprevious_sibling->isa("PPI::Token::Word") 67 11 78
374  
375 11 return $sprevious_sibling->{content} =~ $self->{'_safe_context_regex'};
376 }
377  
378  
379 188 ▶sub get_token_content {
Subroutine get_token_content: called CC=3 SCAR=11.3
Pod documented
380 188 my ($token) = @_;
381  
382 # Retrieve the string's content.
383 188 ▶ if ( $token->isa('PPI::Token::HereDoc') ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($token->isa('PPI::Token::HereDoc')) { } 22 166 188
elsif ($token->isa('PPI::Token::Quote')) { } 166 0 166
384 22 return join( '', $token->heredoc );
385 }
386 elsif ( $token->isa('PPI::Token::Quote') ) {
387  
388 # ->string() strips off the leading and trailing quotation signs.
389 166 return $token->string();
390 }
391  
392 0 return $token->content();
393 }
394  
395  
396 93 ▶sub analyze_string_injections {
Subroutine analyze_string_injections: called CC=2 SCAR=7.0
Pod documented
397 93 my ( $policy, $token ) = @_;
398  
399 93 ▶ my $sql_injections = try {
Subroutine __ANON__: called CC=14 SCAR=26.5
400  
401 # Single quoted strings aren't prone to SQL injection.
402 return
403 93 ▶ if $token->isa('PPI::Token::Quote::Single');
Branch: 1 branch
BranchTrueFalseTotal
if $token->isa("PPI::Token::Quote::Single") 21 72 93
404  
405 # PPI treats HereDoc differently than Quote and QuoteLike for the moment,
406 # this may however change in the future according to the documentation of
407 # PPI.
408 72 my $is_heredoc = $token->isa('PPI::Token::HereDoc');
409  
410 # Retrieve the string's content.
411 72 my $content = get_token_content($token);
412  
413 # Find the list of variables marked as safe using "## SQL safe".
414 # Note: comments will appear at the end of the token, so we need to
415 # determine the ending line number instead of the beginning line
416 # number.
417 72 my $extra_height_span = () = $content =~ /\n/g;
418 72 ▶ my $safe_elements = get_safe_elements(
Branch: 1 branch
BranchTrueFalseTotal
$is_heredoc ? : 10 62 72
419 $policy, #$self
420 $token->line_number()
421  
422 # Heredoc comments will be on the same line as the opening marker.
423 + ( $is_heredoc ? 0 : $extra_height_span ),
424 );
425  
426 # Find all the variables that appear in the string.
427 72 my @variables = @{ String::InterpolatedVariables::extract($content) };
428  
429 # Turn ${foo}, @{foo} and %{foo} into $foo, @foo and %foo.
430 72 my @vars;
431 72 for my $var (@variables) {
432 43 ▶ if ( $var =~ m/^( \$ |@ |% ) \{ \s* ( \w+ ) \s* \}$/x ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($var =~ /^( \$ |@ |% ) \{ \s* ( \w+ ) \s* \}$/x) 1 42 43
433 1 $var = $1 . $2;
434 }
435 43 push @vars, $var;
436 }
437  
438 # Find all the variables that appear in the string.
439 72 my $unsafe_variables = [ grep { !$safe_elements->{$_} } @vars ];
440  
441 # Based on the token type, determine if it is interpolated and report any
442 # unsafe variables.
443 72 ▶ if ( $token->isa('PPI::Token::Quote::Double') ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($token->isa('PPI::Token::Quote::Double')) { } 61 11 72
elsif ($token->isa('PPI::Token::Quote::Interpolate')) { } 1 10 11
elsif ($is_heredoc) { } 10 0 10
444 61 ▶ return $unsafe_variables
Branch: 1 branch
BranchTrueFalseTotal
if scalar @$unsafe_variables != 0 12 49 61
445 if scalar(@$unsafe_variables) != 0;
446 }
447 elsif ( $token->isa('PPI::Token::Quote::Interpolate') ) {
448 1 my $raw_content = $token->content();
449 1 my ($lead) = $raw_content =~ /\A(qq?)([^q])/s;
450 1 ▶ croak "Unknown format for >$raw_content<"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lead 0 1 1
451 if !defined($lead);
452  
453 # Skip single quoted strings.
454 1 ▶ return if $lead eq 'q';
Branch: 1 branch
BranchTrueFalseTotal
if $lead eq "q" 0 1 1
455  
456 1 ▶ return $unsafe_variables
Branch: 1 branch
BranchTrueFalseTotal
if scalar @$unsafe_variables != 0 1 0 1
457 if scalar(@$unsafe_variables) != 0;
458 }
459 elsif ($is_heredoc) {
460 10 my $str = PPIx::QuoteLike->new($token);
461 10 ▶ return unless $str->interpolates;
Branch: 1 branch
BranchTrueFalseTotal
unless $str->interpolates 1 9 10
462  
463 9 ▶ return $unsafe_variables
Branch: 1 branch
BranchTrueFalseTotal
if scalar @$unsafe_variables != 0 6 3 9
464 if scalar(@$unsafe_variables) != 0;
465 }
466  
467 52 return;
468 }
469 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
470 0 print STDERR "Error: $_\n";
471 0 return;
472 93 };
473  
474 93 ▶ return defined($sql_injections)
Branch: 1 branch
BranchTrueFalseTotal
defined $sql_injections ? : 19 74 93
475 ? $sql_injections
476 : [];
477 }
478  
479  
480 100 ▶sub get_safe_elements {
Subroutine get_safe_elements: called CC=5 SCAR=16.8
Pod documented
481 100 my ( $self, $line_number ) = @_;
482  
483 # Validate input and state.
484 croak 'Parsed comments not found'
485 100 ▶ if !defined( $self->{'_sqlsafe'} );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"_sqlsafe"} 0 100 100
486 100 ▶ croak 'A line number is mandatory'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line_number and $line_number =~ /\A\d+\Z/ 0 100 100
Condition33%1/3
defined $line_number and $line_number =~ /\A\d+\Z/
!ll&&!rl&&r
00100
MC/DC0%0/2
defined $line_number and $line_number =~ /\A\d+\Z/
defined $line_number $line_number =~ /\A\d+\Z/
Truth table33%1/3
A and B
A= defined $line_numberB= $line_number =~ /\A\d+\Z/
ABresult
0X0
100
111
487 if !defined($line_number) || ( $line_number !~ /\A\d+\Z/ );
488  
489 # If there's nothing in the cache for that line, return immediately.
490 return {}
491 100 ▶ if !exists( $self->{'_sqlsafe'}->{$line_number} );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"_sqlsafe"}{$line_number} 58 42 100
492  
493 # Return a hash of safe element names.
494 42 return { map { $_ => 1 } @{ $self->{'_sqlsafe'}->{$line_number} } };
495 }
496  
497  
498 116 ▶sub parse_comments {
Subroutine parse_comments: called CC=5 SCAR=16.1
Pod documented
499 116 my ( $self, $doc ) = @_;
500  
501 # Only parse if we haven't done so already.
502 return
503 116 ▶ if defined( $self->{'_sqlsafe'} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_sqlsafe"} 41 75 116
504  
505 # Parse all the comments for this document.
506 75 $self->{'_sqlsafe'} = {};
507 75 ▶ my $comments = $doc->find('PPI::Token::Comment') || [];
Condition100%2/2
$doc->find('PPI::Token::Comment') || []
l!l
2748
MC/DC100%1/1
$doc->find('PPI::Token::Comment') || []
$doc->find('PPI::Token::Comment')
Truth table100%2/2
A
A= $doc->find('PPI::Token::Comment')
Aresult
11
00
508 75 foreach my $comment (@$comments) {
509  
510 # Determine if the line is a "SQL safe" comment.
511 29 my ($safe_elements) = $comment =~ $SQL_SAFE_COMMENTS_REGEX;
512 29 ▶ next if !defined($safe_elements);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $safe_elements 2 27 29
513  
514 # Store list of safe elements for that line.
515 push(
516 27 @{ $self->{'_sqlsafe'}->{ $comment->line_number() } },
517 split( /[\s,]+(?=[\$\@\%\&])/, $safe_elements )
518 );
519 }
520  
521 #print STDERR "SQL safe elements: ", Dumper( $self->{'_sqlsafe'} ), "\n";
522 75 return;
523 }
524  
525  
526 116 ▶sub parse_config_parameters {
Subroutine parse_config_parameters: called CC=7 SCAR=19.5
Pod documented
527 116 my ($self) = @_;
528  
529 116 ▶ if ( !exists( $self->{'_quoting_methods_regex'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"_quoting_methods_regex"}) 75 41 116
530 75 ▶ if ( $self->{'_quoting_methods'} =~ /\w/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_quoting_methods'} =~ /\w/) { } 74 1 75
531 my $regex_components = join(
532 '|',
533 218 grep { $_ =~ /\w/ }
534 74 split( /,?\s+/, $self->{'_quoting_methods'} )
535 );
536 74 $self->{'_quoting_methods_regex'} = qr/^(?:$regex_components)$/x;
537 }
538 else {
539 1 $self->{'_quoting_methods_regex'} = undef;
540 }
541 }
542  
543 116 ▶ if ( !exists( $self->{'_safe_functions_regex'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"_safe_functions_regex"}) 75 41 116
544 75 ▶ if ( $self->{'_safe_functions'} =~ /\w/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_safe_functions'} =~ /\w/) { } 1 74 75
545 my $regex_components = join(
546 '|',
547 1 grep { $_ =~ /\w/ }
548 1 split( /,?\s+/, $self->{'_safe_functions'} )
549 );
550 1 $self->{'_safe_functions_regex'} = qr/^(?:$regex_components)$/x;
551 }
552 else {
553 74 $self->{'_safe_functions_regex'} = undef;
554 }
555 }
556  
557 116 ▶ if ( !exists( $self->{'_safe_context_regex'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"_safe_context_regex"}) 75 41 116
558 75 ▶ if ( $self->{'_safe_context'} =~ /\w/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_safe_context'} =~ /\w/) { } 75 0 75
559 my $regex_components = join(
560 '|',
561 450 grep { $_ =~ /\w/ }
562 75 split( /,?\s+/, $self->{'_safe_context'} )
563 );
564 75 $self->{'_safe_context_regex'} = qr/^(?:$regex_components)$/x;
565 }
566 else {
567 0 $self->{'_safe_context_regex'} = undef;
568 }
569 }
570  
571 116 return;
572 }
573  
574  
575 12 1;
576  
577 # ABSTRACT: Prevent SQL injection in interpolated strings.
578  
579 __END__
↑ Summary