CGIChecker.pm

filter: Statementstmt 5.8% 12 / 207 Branchbran 0.0% 0 / 72 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 22.2% 4 / 18 Podpod 0.0% 0 / 2 totaltotal 5.1% 16 / 314 CC 49 SCAR 41.6
CC
49
Cov
4%
checkHTML
156.0
_pair_compile
132.0
new
56.0
CRAP 64.1
↑ Summary test/allow.pl »
1  
2 package HTML::CGIChecker;
3  
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶ use vars qw ($VERSION @ISA);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 $VERSION = 0.90;
10 1 @ISA = ();
11 }
12  
13 =head1 NAME
14  
15 B<HTML::CGIChecker - A Perl module to detect dangerous HTML code>
16  
17  
18 =head1 SYNOPSIS
19  
20 use HTML::CGIChecker;
21
22 $feedback = '
23 <TABLE CELLPADDING="2"><TR><TD>One column</TD></TR></TABLE><BR>
24 " Arrays & variables "
25
26 Dough > Hi, how are you ?
27
28 And now some Perl code:
29 <PRE>
30 print "<HTML><BODY></BODY></HTML>";
31 </PRE>
32 ';
33  
34 # create the $checker object
35
36 $checker = new HTML::CGIChecker (
37 mode => 'allow',
38 allowclasses => [ qw( tables images ) ],
39 allowtags => [ qw ( B I A U STRONG BR HR ) ],
40 jscript => 0,
41 html => 0,
42 pre => 1,
43 debug => 0,
44 err_tag => 'Tag {tag} is not allowed in {element}.'
45 );
46  
47 # Now you can use it to check any string using its checkHTML()
48 # method. It "remembers" its configuration, so you can reuse it.
49  
50 ($checked_feedback, $Warnings) =
51 $checker->checkHTML ($feedback);
52  
53 # Process the results ...
54  
55 if ($checked_feedback) {
56 # save $checked_feedback to the database ....
57 }
58 else {
59 # print the warnings ...
60 print join ("\n", @{$Warnings});
61 }
62  
63 The example above produces no warning messages and returns
64 $feedback checked and properly HTML escaped. The only HTML "error" -
65 the unescaped "E<gt>" bracket on the fourth line - is autocorrected.
66 One warning message was overriden by a customized version. Potential
67 warnings would not be HTML formatted and HTML safe, because
68 the 'html' parameter is not true.
69  
70  
71 =head1 MOTIVATION
72  
73 Almost every modern website needs some way to get feedback from its users
74 in form of comments that are also visible to other visitors. It is convenient
75 to allow the users to use a limited set of HTML tags in their posts to
76 embold text, create hyperlinks or even include images.
77  
78 The problem araises when the user posts HTML code that breaks the page on
79 which the post is displayed. You must check the
80 posts for dangerous HTML errors and javascripts to prevent a malicious user
81 to render the rest of the page unusable. This module has been created
82 to fulfill this function and also to provide some extra features.
83  
84 Typical HTML validators do not suit well for the above mentioned purpose,
85 because they are way too strict and do not scale well. A small and fast
86 checker that also allows a programmer to deny and allow tags on an individual
87 basis comes as a solution of this problem. Another problem one has to solve
88 while creating a web site that allows HTML user posts is to escape these
89 posts correctly before storing them to the database and displaying them
90 to other users.
91  
92 The currently available module HTML::QuickCheck that should fill the same
93 purpose does not offer some crucial features:
94  
95 Checking of B<correct quoting> - this problem can be fatal, because the
96 common typo when one forgets to close quotes in for example a HREF parameter
97 almost always totally corrupts the rest of a page.
98  
99 B<HTML escaping> of the right parts of the posts - ie. of the non-HTML parts.
100  
101 Denying/allowing of B<javascripts>.
102  
103 Denying/allowing of B<images>, applets, styles, forms and other similar
104 functionality that requires a programmer to be able to deny/allow tags
105 or entire tags classes on an individual basis.
106  
107 Support for the special formatting B<PRE tag>. Please note that the
108 PRE tag has special meaning for this module.
109 Everything that is placed inside PRE block is automatically HTML
110 escaped. The users can use this behaviour to easily post for
111 example code snippets that contain unescaped HTML brackets. All they
112 need is to place the snippet inside a PRE block. They do not need to
113 worry about escaping of the brackets.
114  
115 Ability to B<customize/localize the warning messages> that are returned
116 to the user in case when a problematic HTML in his post is detected.
117  
118 Autocorrection of some "common" errors, for example of chat messages
119 containing unescaped HTML brackets - "peter E<gt> how are you ?".
120 Both unmatched opening and closing HTML brackets are autocorrected.
121  
122 Proper detection of some table closing tags problems that can break the page
123 in some browsers.
124  
125 Conversion of images to appropriate hyperlinks.
126  
127 Automatic prepending of "http://" to URLs which do not start with "http://".
128  
129  
130 =head1 DESCRIPTION
131  
132 HTML::CGIChecker is a module for web developers to parse HTML and to detect
133 HTML code that could break a page in some way.
134 This module is not a HTML validator, but it allows one to check the HTML
135 code that users post to a web application, for example to a discussion
136 board, to prevent them to post a piece of code that would render the rest
137 of a page it is displayed on unusable.
138  
139 Using it one also can deny javascripts, images, tables or any other
140 tags on an individual basis. It also can check for correct quoting
141 and correct URLs.
142  
143 The module can autocorrect some common bad users' behaviour, for
144 example the use of unescaped HTML brackets in a chat room, etc.
145  
146 It is easy to use and very useful in any CGI application in which
147 you want its users to be able to use HTML in their posts to some
148 customizable extent. It is object oriented and designed to be easily
149 extensible.
150  
151 B<This is not a validator>, for validation you need an other
152 solution. This module does not care about correctness of the parsed HTML code
153 at all. All it does care about is whether the HTML code could break a page.
154 HTML tags that are not paired correctly or that cannot be rendered at all
155 can pass this checker. All the names of elements and attributes are not case
156 sensitive.
157  
158 The checker object is created by calling new() constructor of HTML::CGIChecker
159 class.
160  
161  
162 $checker = new HTML::CGIChecker (
163 mode => 'allow',
164 ....
165 );
166  
167  
168 Then you can use the checkHTML() instance method to perform a check on
169 a string using the settings this object has been configured with.
170  
171 ($checked_string, $Warnings) =
172 $checker->checkHTML ($string);
173  
174  
175 B<new() - the constructor>
176  
177 Creates and returns a new checker object that can be configured with
178 parameters that are described below. Default configuration allows only
179 a few harmless inline tags to be used in the HTML code:
180  
181 B I A U STRONG BR
182 EM CITE VAR ABBR Q DFN CODE SUB SUP SAMP KBD ACRONYM
183  
184 Other tags except the special PRE tag are not allowed.
185 Javascripts are by default also not allowed.
186  
187 The various parameters are passed in as a list of B<parameter =E<gt> value>
188 pairs. List of these parameters together with their default values follows:
189  
190 mode => 'allow'
191 allowclasses => []
192 allowtags => [ qw (
193 B I A U STRONG BR EM CITE VAR ABBR Q DFN CODE
194 SUB SUP SAMP KBD ACRONYM
195 ) ]
196 denyclasses => [ keys (%tagclasses) ]
197 denytags => [ qw ( FONT ) ]
198 jscript => 0
199 html => 0
200 pre => 1
201 img_to_link => 0
202 check_http => 1
203 debug => 0
204 nonpairtags => [ qw (
205 IMG HR BR INPUT META AREA COL BASE LINK PARAM
206 ) ]
207 check_attribs => {}
208 err_tag => 'Tag {tag} is not allowed in {element}.'
209 err_javascript => 'Javascript is not allowed in {element}.'
210 err_quote => 'Missing quote in {element}.'
211 err_notclosed => 'Pair tag {tag} was not closed.'
212 err_notopened => 'Pair tag {tag} was not opened.'
213  
214  
215 B<mode>
216  
217 Two modes are available: allow (default) and deny.
218  
219 B<allow>: Error is raised if any tag that is not explicitely
220 allowed is found.
221  
222 B<deny>: Error is raised if an explicitely denied tag is found,
223 any other tags are allowed.
224  
225  
226 B<allowclasses, allowtags>
227  
228 These parameters apply only in the 'allow' mode.
229 Here you can specify the tags you allow the user to use.
230 Allowtags must be a reference to an array of tag names.
231 Allowclasses must be a refernce to an array of class names.
232 Tag class (tag group) is a set of tags that can be allowed or denied all
233 at once by allowing or denying the class. These classes are available:
234  
235 base FRAMESET FRAME HTML BODY HEAD TITLE BASE
236 STYLE SCRIPT META NOSCRIPT NOFRAMES
237 externals APPLET OBJECT LINK IFRAME PARAM
238 forms FORM TEXTAREA SELECT INPUT BUTTON LABEL
239 FIELDSET LEGEND OPTGROUP
240 tables TABLE TR TD TBODY THEAD TFOOT TH COLGROUP
241 COL CAPTION
242 lists UL OL LI DL DT DD
243 images IMG MAP AREA
244 heading H1 H2 H3 H4 H5 H6 H7 H8
245  
246 By default only the above mentioned harmless inline tags are allowed.
247 By default no classes are allowed.
248  
249 B<denyclasses>, B<denytags>
250  
251 These parameters apply only in the 'deny' mode.
252 They work similar to the allowclasses and allowtags
253 parameters. By default B<all> above listed classes plus the FONT tag are
254 denied. All other tags are by default allowed in this mode.
255  
256 B<jscript>
257  
258 This option disables javascript inside HTML elements.
259 You also must ensure that the SCRIPT tag is not allowed to block
260 the javascript completely.
261  
262 0: javascript is not allowed
263 1: javascript is allowed
264 Default: 0
265  
266  
267 B<html>
268  
269 0: messages will not be in HTML format nor HTML escaped -
270 useful for the command line mode
271 1: all warning messages will be in HTML versions and also
272 HTML escaped
273 Default: 0
274  
275 B<pre>
276  
277 0: users will not be allowed to use the special PRE tag
278 1: users will be allowed to use the special PRE tag
279 Default: 1
280  
281 B<img_to_link>
282  
283 0: do not alter images
284 1: convert all images to appropriate links to these
285 images: <IMG SRC="url"> ----> <A HREF="url">url</A>
286 Default: 0
287  
288 B<check_http>
289  
290 0: do not alter URLs
291 1: prepend "http://" to URLs that do not start
292 with "http://", "ftp://" or "mailto:"
293 Default: 1
294
295 Note: the URLs are recognized only in
296 HREF and SRC parameters.
297  
298 B<debug>
299  
300 0: debugging to STDERR is disabled
301 1: debugging to STDERR is enabled
302 Default: 0
303  
304 B<nonpairtags>
305  
306 The tags that are processed as non-pair can be specified here
307 via a reference to an anonymous array.
308 By default these tags are processed as non-pair:
309  
310 IMG HR BR INPUT META AREA COL BASE LINK PARAM
311  
312 B<check_attribs>
313  
314 You also can use the check_attribs parameter to allow the user to use
315 only a limited set of attributes in an element. The parameter is a
316 hash reference, that consists of key->value pairs, in which the key is
317 name of an element, and the value is a reference to an array of attributes.
318 For each element specified in this hash, the user will only be allowed
319 to use the specified attributes.
320  
321 For example, if you define following hash reference:
322  
323 check_attribs => {
324 img => [ 'src', 'width', 'height', 'alt' ]
325 }
326  
327 then the user will be allowed to use ONLY the specified attributes in
328 the <IMG> element. Any other elements are not affected and the user
329 will be allowed to use any attributes in them. Names of the elements
330 and of the attributes are not case sensitive.
331  
332 B<Warning messages> can be redefined by setting these parameters:
333  
334 err_tag = 'Tag {tag} is not allowed in {element}.'
335 err_javascript = 'Javascript is not allowed in {element}.'
336 err_quote = 'Missing quote in {element}.'
337 err_notclosed = 'Pair tag {tag} was not closed.'
338 err_notopened = 'Pair tag {tag} was not opened.'
339  
340 Messages displayed above are the defaults. Special tokens {tag} and {element}
341 are replaced by the appropriate values. You can redefine these messages to
342 localize them.
343  
344  
345 B<checkHTML() - the actual HTML check method>
346  
347  
348 ($checked_string, $Warnings) =
349 $checker->checkHTML ($string);
350  
351  
352 This method accepts only one parameter - the actual string to check.
353  
354 If the string contains anything dangerous or not allowed then this method
355 returns an undefined value and a reference to an array of warning messages
356 that describe the problems that were detected.
357  
358 If the string is safe then checked and escaped version of the
359 string is returned together with an reference to an empty array.
360  
361 Please note the warning messages are not returned as an array, but as a
362 reference to an array, that must be B<dereferenced> when you use it as an
363 array. Usual way to print all the warnings is using the join() function:
364  
365 print join ("<BR>\n", @{$Warnings});
366  
367  
368 =head1 SUPPORT
369  
370 No official support is provided, but I welcome any comments, patches
371 and suggestions on my email. If you suggest a new feature, please justify
372 how it will help the purpose of this module - to provide B<fast> checking
373 for HTML code that breaks pages.
374  
375  
376 =head1 BUGS
377  
378 I am aware of no bugs. But remember, this is NOT a validator - bad HTML may
379 and will pass it. Please let me know if you find any chunk of code that passes
380 it and also breaks a page.
381  
382  
383 =head1 AVAILABILITY
384  
385 http://www.geocities.com/tripiecz/
386  
387  
388 =head1 AUTHOR
389  
390 B<Tomas Styblo>, tripiecz@yahoo.com
391  
392 Prague, the Czech republic
393  
394  
395 =head1 LICENSE
396  
397 HTML::CGIChecker - A Perl module to detect dangerous HTML code
398  
399 Copyright (C) 2000 Tomas Styblo (tripiecz@yahoo.com)
400  
401 This module is free software; you can redistribute it and/or modify it
402 under the terms of either:
403  
404 a) the GNU General Public License as published by the Free Software
405 Foundation; either version 1, or (at your option) any later version,
406 or
407  
408 b) the "Artistic License" which comes with this module.
409  
410 This program is distributed in the hope that it will be useful,
411 but WITHOUT ANY WARRANTY; without even the implied warranty of
412 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either
413 the GNU General Public License or the Artistic License for more details.
414  
415 You should have received a copy of the Artistic License with this
416 module, in the file Artistic. If not, I'll be glad to provide one.
417  
418 You should have received a copy of the GNU General Public License
419 along with this program; if not, write to the Free Software
420 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
421 USA
422  
423  
424 =head1 SEE ALSO
425
426 perl(1).
427  
428  
429 =cut
430  
431 # public:
432 sub new;
433 sub checkHTML;
434  
435 # private:
436 sub _pair_compile;
437 sub _process_element;
438 sub _http;
439 sub _imgtolink;
440 sub _quoting;
441 sub _javascript;
442 sub _pair_saveinfo;
443 sub _allowed_tags;
444 sub _parse_error;
445 sub _pair_check;
446 sub _html_escape;
447  
448 END { }
449  
450 0 ▶sub new {
Subroutine new: not called CC=7 SCAR=40.3
Pod undocumented
451 0 my $class = shift;
452
453 0 ▶ croak ('HTML::CGIChecker - even number of parameters expected.')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 0 0 0
454 if (@_ % 2);
455
456 0 my %tagclasses;
457 0 $tagclasses{'base'} =
458 [ qw ( FRAMESET FRAME HTML BODY HEAD TITLE BASE
459 STYLE SCRIPT META NOSCRIPT NOFRAMES ) ];
460 0 $tagclasses{'externals'} = [ qw ( APPLET OBJECT LINK IFRAME PARAM ) ];
461 0 $tagclasses{'forms'} = [ qw (
462 FORM TEXTAREA SELECT INPUT BUTTON LABEL FIELDSET LEGEND
463 OPTGROUP
464 ) ];
465 0 $tagclasses{'tables'} =
466 [ qw ( TABLE TR TD TBODY THEAD TFOOT TH COLGROUP COL CAPTION ) ];
467 0 $tagclasses{'lists'} = [ qw ( UL OL LI DL DD DT ) ];
468 0 $tagclasses{'images'} = [ qw ( IMG MAP AREA ) ];
469 0 $tagclasses{'heading'} = [ qw ( H1 H2 H3 H4 H5 H6 H7 H8 ) ];
470  
471 # set the defaults
472 0 my $self = {
473 check => '',
474 mode => 'allow',
475 denyclasses => [ keys (%tagclasses) ],
476 denytags => [ qw ( FONT ) ],
477 allowclasses => [],
478 allowtags => [ qw (
479 B I A U STRONG BR EM CITE VAR ABBR Q DFN CODE
480 SUB SUP SAMP KBD ACRONYM
481 ) ],
482 jscript => 0,
483 html => 0,
484 pre => 1,
485 img_to_link => 0,
486 check_http => 1,
487 debug => 0,
488 nonpairtags => [ qw (
489 IMG HR BR INPUT META AREA COL BASE LINK PARAM
490 ) ],
491 check_attribs => {},
492 err_tag => 'Tag {tag} is not allowed in {element}.',
493 err_javascript => 'Javascript is not allowed in {element}.',
494 err_quote => 'Missing quote in {element}.',
495 err_notclosed => 'Pair tag {tag} was not closed.',
496 err_notopened => 'Pair tag {tag} was not opened.',
497 err_attrib => 'Attribute {attrib} is not allowed in {tag}.'
498 };
499  
500 0 bless ($self, $class);
501  
502 # get parameters, overiding the defaults
503 0 ▶ for (my $i = 0; $i <= $#_; $i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $#_) 0 0 0
504 0 ▶ exists ( $self->{lc($_[$i])} ) or
Branch: 1 branch
BranchTrueFalseTotal
exists $$self{lc $_[$i]} or croak('Invalid parameter ' . $_[$i] . '.') 0 0 0
505 croak ('Invalid parameter ' . $_[$i] . '.');
506 0 $self->{lc($_[$i])} = $_[($i + 1)];
507 }
508  
509 # convert to uppercase
510 0 map ($_ = uc($_), @{$self->{'allowtags'}});
511 0 map ($_ = uc($_), @{$self->{'denytags'}});
512  
513 0 my $class;
514 0 foreach $class (keys(%tagclasses)) {
515 0 map ($_ = uc($_), @{$tagclasses{$class}});
516 }
517
518 0 map ($_ = uc($_), @{$self->{'nonpairtags'}});
519
520 0 my $element;
521 0 foreach $element (keys(%{$self->{'check_attribs'}})) {
522 0 map ($_ = uc($_), @{$self->{'check_attribs'}->{$element}});
523 0 ▶ if ($element ne uc($element)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($element ne uc $element) 0 0 0
524 0 my $ucelement = uc($element);
525 $self->{'check_attribs'}->{$ucelement} =
526 0 $self->{'check_attribs'}->{$element};
527 0 delete($self->{'check_attribs'}->{$element});
528 }
529 }
530  
531 # compiles allowed/denied tag data
532 0 $self->_pair_compile (\%tagclasses);
533  
534 0 return $self;
535 }
536  
537  
538 0 ▶sub checkHTML {
Subroutine checkHTML: not called CC=12 SCAR=50.5
Pod undocumented
539 0 my $self = shift;
540 0 my $in = shift;
541 0 my $out; # processed input to return
542 0 my $premode = 0; # indicates we are in a PRE block
543
544 0 $self->{'_errors'} = [];
545 0 $self->{'_opentags'} = {};
546 0 $self->{'_closetags'} = {};
547  
548 0 my @tokens = split(/(<[^<]*?>)/s, $in);
549 0 my $token;
550 0 foreach $token (@tokens) {
551 0 ▶ if (index($token, '<') != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($token, "<") != 0) 0 0 0
552 # This token is not a HTML element.
553 # Jump to the next token.
554 0 $out .= $self->_html_escape($token);
555 0 next;
556 }
557
558 # This token is a HTML element.
559 0 $self->{'_element'} = $token; # element = the whole <.*> thing
560 0 ($self->{'_tag'}) = $token =~ m|^<\s*(/?\w+)|s; # name of this tag
561 0 ▶ next if (not $self->{'_tag'});
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_tag"} 0 0 0
562 0 $self->{'_tag'} = uc($self->{'_tag'});
563
564 # generetes the abstag
565 0 ▶ if (index($self->{'_tag'}, '/') == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($self->{'_tag'}, '/') == 0) { } 0 0 0
566 0 $self->{'_abstag'} = substr ($self->{'_tag'}, 1);
567 }
568 else {
569 0 $self->{'_abstag'} = $self->{'_tag'};
570 }
571
572 # the PRE feature
573 # end this pass if PRE is allowed and we are in a PRE block
574
575 0 ▶ if ($self->{'pre'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"pre"}) 0 0 0
576 0 ▶ if (not $premode and $self->{'_tag'} eq 'PRE') {
Branch: 2 branches
BranchTrueFalseTotal
if (not $premode and $self->{'_tag'} eq 'PRE') { } 0 0 0
elsif ($premode and $self->{'_tag'} eq '/PRE') { } 0 0 0
Condition0%0/3
not $premode and $self->{"_tag"} eq "PRE"
!ll&&!rl&&r
000
MC/DC0%0/2
not $premode and $self->{"_tag"} eq "PRE"
not $premode $self->{"_tag"} eq "PRE"
Truth table0%0/3
not(A) and B
A= not $premodeB= $self->{"_tag"} eq "PRE"
ABresult
0X0
100
111
577 0 $out .= $self->{'_element'};
578 0 $premode = 1;
579 0 $self->_pair_saveinfo();
580 0 next;
581 }
582 ▶ elsif ($premode and $self->{'_tag'} eq '/PRE') {
Condition0%0/3
$premode and $self->{"_tag"} eq "/PRE"
!ll&&!rl&&r
000
MC/DC0%0/2
$premode and $self->{"_tag"} eq "/PRE"
$premode $self->{"_tag"} eq "/PRE"
Truth table0%0/3
A and B
A= $premodeB= $self->{"_tag"} eq "/PRE"
ABresult
0X0
100
111
583 0 $out .= $self->{'_element'};
584 0 $premode = 0;
585 0 $self->_pair_saveinfo();
586 0 next;
587 }
588
589 0 ▶ if ($premode) {
Branch: 1 branch
BranchTrueFalseTotal
if ($premode) 0 0 0
590 0 $out .= $self->_html_escape($self->{'_element'});
591 0 next;
592 }
593 }
594
595 # If PRE is allowed, then we get to this point only if the current
596 # element is not inside a PRE block.
597 #
598 # This method calls all the methods that process the current element.
599 # Override this method in your subclass to add your own methods.
600 0 $self->_process_element();
601
602 # Current element is pushed to the end of the output buffer.
603 0 $out .= $self->{'_element'};
604 }
605 # END of the loop
606
607 0 $self->{'_element'} = '';
608 0 $self->{'_tag'} = '';
609 0 $self->{'_abstag'} = '';
610
611 0 $self->_pair_check ($self->{'_opentags'}, $self->{'err_notclosed'});
612 0 $self->_pair_check ($self->{'_closetags'}, $self->{'err_notopened'});
613  
614 # We make a copy of the array of errors to prevent memory leakage
615 # that can occur if a bad programmer does not destroy the reference
616 # to this array after he is finished with it. If we do not make this copy
617 # then the whole object would not be freed in this case.
618
619 0 my @ret_errors = @{$self->{'_errors'}};
620  
621 0 ▶ if (@ret_errors) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ret_errors) { } 0 0 0
622 0 return (undef, \@ret_errors);
623 }
624 else {
625 0 return ($out, \@ret_errors);
626 }
627 }
628  
629 ##############################################################################
630 ##################### PRIVATE METHODS ##########################
631 ##############################################################################
632  
633 # "compiles" the array of allowed/denied tags
634 # resolves tag classes and merges them with individualy specified tags
635  
636 0 ▶sub _pair_compile {
Subroutine _pair_compile: not called CC=11 SCAR=48.8
637 0 my $self = shift;
638 0 my $tagclasses = shift; # reference to predefined tag classes
639 0 my @allow;
640 my @deny;
641
642 0 ▶ if ($self->{'mode'} eq "allow") {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'mode'} eq 'allow') { } 0 0 0
elsif ($self->{'mode'} eq 'deny') { } 0 0 0
643 # allow mode = error if any not explicitely allowed tag is found
644 0 my $allowclass;
645 0 foreach $allowclass (@{$self->{'allowclasses'}}) {
646 0 push(@allow,@{$tagclasses->{$allowclass}})
647 }
648 0 my $tag;
649 0 foreach $tag (@{$self->{'allowtags'}}) {
650 0 ▶ push (@allow, $tag) if (not grep (($_ eq $tag), @allow));
Branch: 1 branch
BranchTrueFalseTotal
unless grep(($_ eq $tag), @allow) 0 0 0
651 }
652 0 ▶ $self->{'debug'} and
Branch: 1 branch
BranchTrueFalseTotal
$self->{"debug"} and warn 'HTML::CGIChecker DEBUG: @allow = ' . join(",", @allow) 0 0 0
653 warn('HTML::CGIChecker DEBUG: @allow = '.join(",", @allow));
654 }
655 elsif ($self->{'mode'} eq "deny") {
656 # deny mode = error if any denied tag is found, everything other is OK
657 0 my $denyclass;
658 0 foreach $denyclass (@{$self->{'denyclasses'}}) {
659 0 push (@deny, @{$tagclasses->{$denyclass}})
660 }
661 0 my $tag;
662 0 foreach $tag (@{$self->{'denytags'}}) {
663 0 ▶ push (@deny, $tag) if (not grep (($_ eq $tag), @deny));
Branch: 1 branch
BranchTrueFalseTotal
unless grep(($_ eq $tag), @deny) 0 0 0
664 }
665 0 ▶ $self->{'debug'} and
Branch: 1 branch
BranchTrueFalseTotal
$self->{"debug"} and warn 'HTML::CGIChecker DEBUG: @deny = ' . join(",", @deny) 0 0 0
666 warn('HTML::CGIChecker DEBUG: @deny = '.join(",", @deny));
667 }
668 else {
669 0 croak('HTML::CGIChecker - mode has to be either "allow" or "deny".')
670 }
671  
672 # store refs to the compiled arrays
673 0 $self->{'_allow'} = \@allow;
674 0 $self->{'_deny'} = \@deny;
675 }
676  
677  
678 # Processes the current element.
679 # NOTE: The order in which these methods are called matters !
680  
681 0 ▶sub _process_element {
Subroutine _process_element: not called CC=1 SCAR=6.9
682 0 my $self = shift;
683 0 $self->_http();
684 0 $self->_imgtolink();
685 0 $self->_quoting();
686 0 $self->_javascript();
687 0 $self->_check_attribs();
688 0 $self->_pair_saveinfo();
689 0 $self->_allowed_tags();
690 }
691  
692  
693 # implements the check_http option
694  
695 0 ▶sub _http {
Subroutine _http: not called CC=3 SCAR=24.8
696 0 my $self = shift;
697 0 ▶ if ($self->{'check_http'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"check_http"}) 0 0 0
698 $self->{'_element'} =~ s!
699 ^<
700 (.+) # 1
701 (href|src)\s*=\s* # 2; MSIE allows the spaces ..
702 (")? # 3 "
703 (.*?) # 4
704 (".*>|\s.*>|>)$ # 5 "
705 !<$1$2=$3http://$4$5!six if
706 0 ▶ ($self->{'_element'} !~
Branch: 1 branch
BranchTrueFalseTotal
if not $self->{"_element"} =~ m[ (http:// |mailto: |ftp:// |telnet:// |file:// ) ]six 0 0 0
707 m!
708 (http://
709 |mailto:
710 |ftp://
711 |telnet://
712 |file://
713 )
714 !xis);
715 }
716 }
717  
718  
719 # implements the img_to_link option
720  
721 0 ▶sub _imgtolink {
Subroutine _imgtolink: not called CC=2 SCAR=17.9
722 0 my $self = shift;
723 0 ▶ if ($self->{'img_to_link'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"img_to_link"}) 0 0 0
724 0 $self->{'_element'} =~ s!
725 ^<
726 img.+src\s*=\s* # MSIE allows the spaces ..
727 "? # "
728 (.*?) # $1
729 (".*>|\s.*>|>)$ # "
730 !<a href="$1">$1</a>!six;
731 }
732 }
733  
734  
735 # checks the element for correct quoting
736  
737 0 ▶sub _quoting {
Subroutine _quoting: not called CC=2 SCAR=17.9
738 0 my $self = shift;
739 0 ▶ if ($self->{'_element'} =~ tr/"/"/ % 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_element"} =~ tr/"// % 2) 0 0 0
740 0 push (@{$self->{'_errors'}},
741 0 $self->_parse_error ($self->{'err_quote'}));
742 }
743 }
744  
745  
746 # checks the element for a javascript
747  
748 0 ▶sub _javascript {
Subroutine _javascript: not called CC=4 SCAR=30.0
749 0 my $self = shift;
750 0 ▶ if (not $self->{'jscript'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{"jscript"}) 0 0 0
751 0 ▶ if ($self->{'_element'} =~ /javascript/i or
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_element"} =~ /javascript/i or $self->{"_element"} =~ /\son\w+\s*=/i) 0 0 0
Condition0%0/3
$self->{"_element"} =~ /javascript/i or $self->{"_element"} =~ /\son\w+\s*=/i
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_element"} =~ /javascript/i or $self->{"_element"} =~ /\son\w+\s*=/i
$self->{"_element"} =~ /javascript/i $self->{"_element"} =~ /\son\w+\s*=/i
Truth table0%0/3
A or B
A= $self->{"_element"} =~ /javascript/iB= $self->{"_element"} =~ /\son\w+\s*=/i
ABresult
1X1
011
000
752 $self->{'_element'} =~ /\son\w+\s*=/i) {
753 0 push (@{$self->{'_errors'}},
754 0 $self->_parse_error ($self->{'err_javascript'}));
755 }
756 }
757 }
758  
759  
760 0 ▶sub _check_attribs {
Subroutine _check_attribs: not called CC=4 SCAR=30.0
761 0 my $self = shift;
762 0 my $element = $self->{'_element'};
763
764 0 ▶ if (ref($self->{'check_attribs'}->{$self->{'_abstag'}})) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"check_attribs"}{$self->{"_abstag"}}) 0 0 0
765 0 $element =~ s/^<\w+\s*//s;
766 0 $element =~ s|/?>$||;
767 0 my @pairs = split(/\s+/, $element);
768 0 my $pair;
769 0 foreach $pair (@pairs) {
770 0 my ($attrib) = split(/=/, $pair);
771 0 $attrib = uc($attrib);
772 0 ▶ if (not grep($attrib eq $_,
Branch: 1 branch
BranchTrueFalseTotal
unless (grep(($attrib eq $_), @{$self->{"check_attribs"}{$self->{"_abstag"}};})) 0 0 0
773 0 @{$self->{'check_attribs'}->{$self->{'_abstag'}}})) {
774 0 $self->{'_attrib'} = $attrib;
775 0 push (@{$self->{'_errors'}},
776 0 $self->_parse_error ($self->{'err_attrib'}));
777 }
778 }
779 }
780 }
781  
782  
783 # Works with counters of tags, so we can later say if there are some tags that
784 # are not correctly either closed or opened.
785 # This implementation prevents a user to place a closing tag before the opening
786 # one and thus make the checker to think it was correctly closed.
787  
788 0 ▶sub _pair_saveinfo {
Subroutine _pair_saveinfo: not called CC=5 SCAR=34.0
789 0 my $self = shift;
790
791 0 ▶ if (index($self->{'_tag'}, '/') == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (index($self->{'_tag'}, '/') == 0) { } 0 0 0
elsif (not grep(($_ eq $self->{'_abstag'}), @{$$self{'nonpairtags'};})) { } 0 0 0
792 # this is a closing tag
793 0 ▶ if (not grep ( ($_ eq $self->{'_abstag'}),
Branch: 1 branch
BranchTrueFalseTotal
if (not grep(($_ eq $self->{"_abstag"}), @{$$self{"nonpairtags"};})) 0 0 0
794 0 @{$self->{'nonpairtags'}})) {
795 0 ▶ if ($self->{'_opentags'}->{$self->{'_abstag'}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_opentags'}{$self->{'_abstag'}}) { } 0 0 0
796 0 $self->{'_opentags'}->{$self->{'_abstag'}}--;
797 }
798 else {
799 0 $self->{'_closetags'}->{$self->{'_abstag'}}++;
800 }
801 }
802 }
803 elsif (not grep ( ($_ eq $self->{'_abstag'}),
804 0 @{$self->{'nonpairtags'}})) {
805 # this is an opening tag
806 0 $self->{'_opentags'}->{$self->{'_abstag'}}++;
807 }
808 }
809  
810  
811 # checks if a given tag is allowed
812  
813 0 ▶sub _allowed_tags {
Subroutine _allowed_tags: not called CC=4 SCAR=30.0
814 0 my $self = shift;
815 0 ▶ if ($self->{'mode'} eq "allow") {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'mode'} eq 'allow') { } 0 0 0
816 0 grep ( ($_ eq $self->{'_abstag'}), @{$self->{'_allow'}}) or
817 0 push (@{$self->{'_errors'}},
818 0 ▶ $self->_parse_error ($self->{'err_tag'}));
Branch: 1 branch
BranchTrueFalseTotal
grep(($_ eq $self->{"_abstag"}), @{$$self{"_allow"};}) or push @{$$self{"_errors"};}, $self->_parse_error($self->{"err_tag"}) 0 0 0
819 } else {
820 0 grep ( ($_ eq $self->{'_abstag'}), @{$self->{'_deny'}}) and
821 0 push (@{$self->{'_errors'}},
822 0 ▶ $self->_parse_error ($self->{'err_tag'}));
Branch: 1 branch
BranchTrueFalseTotal
grep(($_ eq $self->{"_abstag"}), @{$$self{"_deny"};}) and push @{$$self{"_errors"};}, $self->_parse_error($self->{"err_tag"}) 0 0 0
823 }
824 }
825  
826  
827 # processes the error messages
828  
829 0 ▶sub _parse_error {
Subroutine _parse_error: not called CC=2 SCAR=17.9
830 0 my $self = shift;
831 0 my ($error) = @_;
832 0 my $element = $self->{'_element'};
833 0 my $tag = $self->{'_tag'};
834 0 my $attrib = $self->{'_attrib'};
835  
836 0 ▶ if ($self->{'html'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'html'}) { } 0 0 0
837 0 $element = $self->_html_escape ($element);
838 0 $tag = '<strong>&lt;' . $tag . '&gt;</strong>';
839 0 $element = '<strong>' . $element . '</strong>';
840 0 $attrib = '<strong>' . $attrib . '</strong>';
841 }
842 0 else { $tag = "<$tag>" }
843  
844 0 $error =~ s/{tag}/$tag/;
845 0 $error =~ s/{element}/$element/;
846 0 $error =~ s/{attrib}/$attrib/;
847 0 $error =~ s/\n+|\r+|\s+/ /g;
848 0 return $error;
849 }
850  
851  
852 # raises an error if a badly paired tag is found
853  
854 0 ▶sub _pair_check {
Subroutine _pair_check: not called CC=3 SCAR=24.8
855 0 my $self = shift;
856 0 my ($Tags, $error) = @_;
857 0 my ($count);
858
859 0 ▶ while ( ($self->{'_tag'}, $count) = each (%{$Tags})) {
Branch: 1 branch
BranchTrueFalseTotal
if (($self->{"_tag"}, $count) = each %{$Tags;}) 0 0 0
860 0 ▶ if ($count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count) 0 0 0
861 0 push (@{$self->{'_errors'}},
862 $self->_parse_error ($error));
863 }
864 }
865 }
866  
867  
868 # Escapes some dangerous characters.
869 # Ampersand "&" is escaped only if it is not part of a HTML entity.
870 # Therefore, users can post HTML entities. Ampersands that are part
871 # of an ordinary text are still properly escaped.
872 # Thanks to godless@hermes.slipstream.com for this idea.
873  
874 0 ▶sub _html_escape {
Subroutine _html_escape: not called CC=2 SCAR=17.9
875 0 my $self = shift;
876 0 my ($in) = @_;
877  
878 0 for ($in) {
879 0 s/&(?!\w+;)/&amp;/g;
880 0 s/>/&gt;/g;
881 0 s/</&lt;/g;
882 0 s/"/&quot;/g;
883 }
884 0 return $in;
885 }
886  
887  
888 1 1;
↑ Summary test/allow.pl »