SafeBrowsing3/Lookup.pm untested

filter: Statementstmt 0.0% 0 / 132 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 27 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 211 SCAR 56.1
CC
16
Cov
0%
lookup
42.0
canonical_uri
42.0
parse
12.0
CRAP 272.0
1 package Net::Google::SafeBrowsing3::Lookup;
2  
3 use strict;
4 use warnings;
5  
6 use Carp;
7 use LWP::UserAgent;
8 use URI;
9 use Text::Trim;
10  
11 our $VERSION = '0.3';
12  
13 =head1 NAME
14  
15 Net::Google::SafeBrowsing3::Lookup - Perl extension for the Google Safe Browsing v3 Lookup API.
16  
17 =head1 SYNOPSIS
18  
19 use Net::Google::SafeBrowsing3::Lookup;
20  
21 my $gsb = Net::Google::SafeBrowsing3::Lookup->new(
22 key => "my key",
23 );
24  
25 my %match = $gsb->lookup(url => 'http://www.gumblar.cn/');
26
27 if ($match{'http://www.gumblar.cn/'} eq 'malware') {
28 print "http://www.gumblar.cn/ is flagged as a dangerous site\n";
29 }
30  
31 my %matches = $gsb->lookup(urls => ['http://www.gumblar.cn/', 'http://flahupdate.co.cc']);
32 foreach my $url (keys %matches) {
33 print $url, " is ", $matches{$url}, "\n";
34 }
35  
36 =head1 DESCRIPTION
37  
38 Net::Google::SafeBrowsing3::Lookup implements the Google Safe Browsing v3.1 Lookup API. See the API documentation at L<https://developers.google.com/safe-browsing/lookup_guide>.
39  
40 If you need to check more than 10,000 URLs a day, you need to use L<Net::Google::SafeBrowsing3>.
41  
42 The source code is available on github at L<https://github.com/juliensobrier/Net-Google-SafeBrowsing3>.
43  
44 IMPORTANT: Google Safe Browsing v3.1 requires a different key than v3.0.
45  
46 =head1 CONSTRUCTOR
47  
48 =over 4
49  
50 =back
51  
52 =head2 new()
53  
54 Create a Net::Google::SafeBrowsing3::Lookup object
55  
56 my $gsb = Net::Google::SafeBrowsing3::Lookup->new(
57 key => "my key",
58 debug => 0,
59 );
60  
61 Arguments
62  
63 =over 4
64  
65 =item key
66  
67 Required. Your Google Safe Browsing API key
68  
69 =item debug
70  
71 Optional. Set to 1 to enable debugging. 0 (disabled) by default.
72  
73 The debug output maybe quite large and can slow down significantly the update and lookup functions.
74  
75 =item errors
76  
77 Optional. Set to 1 to show errors to STDOUT. 0 (disabled by default).
78  
79 =item version
80  
81 Optional. Google Safe Browsing version. 3.1 by default
82  
83 =item delay
84  
85 Optional. Delay, in seconds, between 2 requests to the Google server. See the C<lookup> function for more details. 0 (no delay) by default
86  
87 =back
88  
89 =cut
90  
91 sub new {
92 my ($class, %args) = @_;
93  
94 my $self = { # default arguments
95 key => '',
96 version => '3.1',
97 debug => 0,
98 delay => 0,
99 errors => 1,
100 last_error => '',
101  
102 %args,
103 };
104  
105 bless $self, $class or croak "Can't bless $class: $!";
106 return $self;
107 }
108  
109  
110 =head1 PUBLIC FUNCTIONS
111  
112 =over 4
113  
114 =back
115  
116 =head2 lookup()
117  
118 Lookup a list URLs against the Google Safe Browsing v3 lists.
119  
120 my %match = $gsb->lookup(url => 'http://www.gumblar.cn');
121  
122 Returns a hash C<url> => C<Google match>. The possible list of values for C<Google match> are: "ok" (no match), "malware", "phishing", "malware,phishing" (match both lists) and "error".
123  
124 Arguments
125  
126 =over 4
127  
128 =item url
129  
130 Optional. Single URL to lookup.
131  
132 =item urls
133  
134 Optional. List of URLs to lookup.
135  
136 The Lookup API allows only 10,000 URL checks a day. if you need more, use the L<Net::Google::SafeBrowsing3> library.
137  
138 Each requests must contain 500 URLs at most. The lookup() method will split the list of URLS in blocks of 500 URLs if needed.
139  
140 =item delay
141  
142 Optional. If more than 500 URLs are checked, wait C<delay> seconds between consecutive requests to avoid rate limiting by Google.
143  
144 =back
145  
146 =cut
147  
148 sub lookup {
149 my ($self, %args) = @_;
150 my $url = $args{url} || '';
151 my @inputs = @{ $args{urls} || []};
152 my $delay = $args{delay} || $self->{delay} || 0;
153  
154  
155 if ($url ne '') {
156 push(@inputs, $url);
157 }
158  
159 # Max is 500 URLs per request
160 my %results = ();
161  
162 my $count = 0;
163 while (scalar @inputs > 0) {
164 my @urls = splice(@inputs, 0, 500);
165  
166 my $body = scalar(@urls);
167 foreach my $input (@urls) {
168 my $canonical = $self->canonical_uri($input);
169 $body .= "\n$canonical";
170 $self->debug("$input => $canonical\n");
171 }
172 $self->debug("BODY:\n$body\n\n");
173
174 my $url = "https://sb-ssl.google.com/safebrowsing/api/lookup?client=perl&key=" . $self->{key} . "&appver=$VERSION&pver=" . $self->{version};
175 sleep $delay if ($delay > 0 && $count > 0);
176 my $res = $self->ua->post($url, Content => $body);
177
178 if ($res->code == 400) {
179 $self->error("Invalid request");
180 %results = ( %results, $self->errors(@urls) );
181 }
182 elsif ($res->code == 401) {
183 $self->error("Invalid API key");
184 %results = ( %results, $self->errors(@urls) );
185 }
186 elsif ($res->code == 503) {
187 $self->error("Server error, client may have sent too many requests");
188 %results = ( %results, $self->errors(@urls) );
189 }
190 else {
191 %results = ( %results, $self->parse(response => $res, urls => [@urls]) );
192 }
193  
194 $count++;
195 }
196  
197 return %results;
198 }
199  
200  
201 sub parse {
202 my ($self, %args) = @_;
203 my $response = $args{response} || croak "Missing response\n";;
204 my @urls = @{ $args{urls} || []};
205  
206  
207 if ($response->code == 204) {
208 $self->debug("No match\n");
209 return map { $_ => 'ok' } @urls;
210 }
211  
212 my %results = ();
213 my @lines = split /\n/, $response->content;
214  
215 if (scalar @urls != scalar @lines) {
216 $self->error("Number of URLs in the reponse does not match the number of URLs in the request");
217 $self->error( scalar(@urls) . "/" . scalar(@lines));
218 $self->error($response->content);
219 return $self->errors(@urls);
220 }
221  
222 for(my $i = 0; $i < scalar(@urls); $i++) {
223 $results{$urls[$i]} = $lines[$i];
224 }
225  
226 return %results;
227 }
228  
229 sub errors {
230 my ($self, @urls) = @_;
231  
232 return map { $_ => 'error' } @urls;
233 }
234  
235  
236 sub ua {
237 my ($self, %args) = @_;
238  
239 if (! exists $self->{ua}) {
240 my $ua = LWP::UserAgent->new;
241 $ua->timeout(60);
242  
243 $self->{ua} = $ua;
244 }
245  
246 return $self->{ua};
247 }
248  
249  
250 sub debug {
251 my ($self, $message) = @_;
252  
253 print $message if ($self->{debug} > 0);
254 }
255  
256  
257 sub error {
258 my ($self, $message) = @_;
259  
260 print "ERROR - ", $message, "\n" if ($self->{debug} > 0 || $self->{errors} > 0);
261 $self->{last_error} = $message;
262 }
263  
264 sub canonical_uri {
265 my ($self, $url) = @_;
266  
267 $url = trim $url;
268  
269 # Special case for \t \r \n
270 while ($url =~ s/^([^?]+)[\r\t\n]/$1/sgi) { }
271  
272 my $uri = URI->new($url)->canonical; # does not deal with directory traversing
273  
274 # $self->debug("0. $url => " . $uri->as_string . "\n");
275  
276
277 if (! $uri->scheme() || $uri->scheme() eq '') {
278 $uri = URI->new("http://$url")->canonical;
279 }
280  
281 $uri->fragment('');
282  
283 my $escape = $uri->as_string;
284  
285 # Reduce double // to single / in path
286 while ($escape =~ s/^([a-z]+:\/\/[^?]+)\/\//$1\//sgi) { }
287  
288  
289 # Remove empty fragment
290 $escape =~ s/#$//;
291  
292 # canonial does not handle ../
293 # $self->debug("\t$escape\n");
294 while($escape =~ s/([^\/])\/([^\/]+)\/\.\.([\/?].*)?$/$1$3/gi) { }
295  
296 # May have removed ending /
297 # $self->debug("\t$escape\n");
298 $escape .= "/" if ($escape =~ /^[a-z]+:\/\/[^\/\?]+$/);
299 $escape =~ s/^([a-z]+:\/\/[^\/]+)(\?.*)$/$1\/$2/gi;
300 # $self->debug("\t$escape\n");
301  
302 # other weird case if domain = digits only, try to translte it to IP address
303 if ((my $domain = URI->new($escape)->host) =~/^\d+$/) {
304 my $ip = num2ip($domain);
305  
306 if (validaddr($ip)) {
307 $uri = URI->new($escape);
308 $uri->host($ip);
309  
310 $escape = $uri->as_string;
311 }
312 }
313  
314 # $self->debug("1. $url => $escape\n");
315  
316 # Try to escape the path again
317 $url = $escape;
318 while (($escape = URI::Escape::uri_unescape($url)) ne $escape) { # wrong for %23 -> #
319 $url = $escape;
320 }
321 # while (($escape = URI->new($url)->canonical->as_string) ne $escape) { # breask more unit tests than previous
322 # $url = $escape;
323 # }
324  
325 # Fix for %23 -> #
326 while($escape =~ s/#/%23/sgi) { }
327  
328 # $self->debug("2. $url => $escape\n");
329  
330 # Fix over escaping
331 while($escape =~ s/^([^?]+)%%(%.*)?$/$1%25%25$2/sgi) { }
332  
333 # URI has issues with % in domains, it gets the host wrong
334  
335 # 1. fix the host
336 # $self->debug("Domain: " . URI->new($escape)->host . "\n");
337 my $exception = 0;
338 while ($escape =~ /^[a-z]+:\/\/[^\/]*([^a-z0-9%_.-\/:])[^\/]*(\/.*)$/) {
339 my $source = $1;
340 my $target = sprintf("%02x", ord($source));
341  
342 $escape =~ s/^([a-z]+:\/\/[^\/]*)\Q$source\E/$1%\Q$target\E/;
343  
344 $exception = 1;
345 }
346  
347 # 2. need to parse the path again
348 if ($exception && $escape =~ /^[a-z]+:\/\/[^\/]+\/(.+)/) {
349 my $source = $1;
350 my $target = URI::Escape::uri_unescape($source);
351  
352 # print "Source: $source\n";
353 while ($target ne URI::Escape::uri_unescape($target)) {
354 $target = URI::Escape::uri_unescape($target);
355 }
356  
357
358 $escape =~ s/\/\Q$source\E/\/$target/;
359  
360 while ($escape =~ s/#/%23/sgi) { } # fragement has been removed earlier
361 while ($escape =~ s/^([a-z]+:\/\/[^\/]+\/.*)%5e/$1\&/sgi) { } # not in the host name
362 # while ($escape =~ s/%5e/&/sgi) { }
363  
364 while ($escape =~ s/%([^0-9a-f]|.[^0-9a-f])/%25$1/sgi) { }
365 }
366  
367 # $self->debug("$url => $escape\n");
368 # $self->debug(URI->new($escape)->as_string . "\n");
369  
370 return URI->new($escape);
371 }
372  
373  
374  
375 =head1 SEE ALSO
376  
377 See L<Net::Google::SafeBrowsing3> for the implementation of Google Safe Browsing v3 API.
378  
379 =head1 AUTHOR
380  
381 Julien Sobrier, E<lt>jsobrier@zscaler.comE<gt> or E<lt>julien@sobrier.netE<gt>
382  
383 =head1 COPYRIGHT AND LICENSE
384  
385 Copyright (C) 2015 by Julien Sobrier
386  
387 This library is free software; you can redistribute it and/or modify
388 it under the same terms as Perl itself, either Perl version 5.8.8 or,
389 at your option, any later version of Perl 5 you may have available.
390  
391  
392 =cut
393  
394 1;