This script demonstrates a use of
HTML::Parser to determine if a web page contains a script tag, or if an html tag contains an event attribute.
I realize that this script takes what I'd call an exclusive method of approval (does the page contain something on a banned list?) rather than an inclusive method (does the page contain something not on an approved list) and is therefore more vulnerable to trickery or changes/ additions to what browsers think is an acceptable javascript event.
I hope this script is useful, but you've been warned. As always, your comments, criticisms and baseless accusations are welcome.
Update
Removed the event list and added dws' suggestion for a regex to search for /on\w+/
Added belg4mit's suggestions :
-
elements passed to check_attrs will get URI decoded
-
added mocha & data as forbidden protocols. If anyone has further suggestions, or a list of pseudo-protocols that should be included, I'd love to see it.
- added check for javascript entities
script doesn't die on first error found anymore. Cleaned up output a bit.
#! perl -w
use HTML::Parser;
use LWP::Simple;
use URI::Escape;
use strict;
my $fn = shift;
$fn || die "supply a url to parse\n";
my $f = get ($fn) || die "unable to get $fn\n";
HTML::Parser->new(
default_h => [\&check_attrs, 'text, tagname, attr'],
+
)->parse($f ) || die $!;
sub check_attrs {
my @forbiddenprotos= qw(javascript mocha data);
my $line = shift;
my $tagname = shift;
return unless $tagname;
$tagname = uri_unescape($tagname);
print "found script tag.\n\t$line\n" if $tagname eq "script";
my $attr = shift;
my $attrs = uri_unescape(join " ", keys %$attr);
my $attrvals = uri_unescape(join " ", values %$attr);
print "events $1 found.\n\t$line\n" if $attrs=~/\b(on\w+)/;
foreach (@forbiddenprotos) {
print "$_ protocol found.\n\t$line\n" if $attrvals=~/\b$_:/;
}
print "javascript entity found.\n\t$line\n" if $attrvals=~/\&\{/;
}